I have multiple processing units that might exist in an array, each with their own parameters. I would like to communicate the parameters of each processing unit using the context pattern after it was suggested as a solution to another question. However, I am unable to find simple C++ examples of the pattern online. I have made a simplified implementation below for your inspection. The code works and compiles just fine, but am I implementing the pattern correctly? Any and all suggestions for style improvements would be most welcome.
#include <iostream>
#include <sstream>
#include <map>
class cParamsContext
{
typedef std::map<std::string, float> myMap_t; //Make the return type of getter less wordy
myMap_t paramMap;
public:
cParamsContext()
{
paramMap["a0"] = 1.f;
paramMap["a1"] = 2.f;
}
myMap_t const& getMap() const {return paramMap;} //Return read-only alias
};
class cProcessUnit
{
float parameter;
int id;
public:
cProcessUnit(cParamsContext &contextObj, int id_) : parameter (0.f), id(id_)
{
std::stringstream idStream;
idStream << id;
std::string key = std::string( "a" + idStream.str() );
if(contextObj.getMap().find( key ) != contextObj.getMap().end())
parameter = contextObj.getMap().find( key )->second; // https://stackoverflow.com/questions/10402354/using-overloaded-operator-via-an-accessor-function#10402452
}
float getParam() {return parameter;}
};
int main(int argc, char *argv[])
{
cParamsContext contextObj;
for (int nn=0; nn<3; nn++)
{
cProcessUnit temp(contextObj, nn);
std::cout << "Processing unit " << nn << " param = " << temp.getParam() << std::endl;
}
}
Furthermore, can you suggest how I could make the parameters within each class update themselves should the parameter map change?
The output looks like this incase you were interested . . . .
Processing unit 0 param = 1
Processing unit 1 param = 2
Processing unit 2 param = 0
This does look like a valid implementation. Does it pass your tests? I’m not experienced using a context pattern in this particular way, but it does look fine to me.
As for updating values, I’m currently doing something very similar in a project I’ve been assigned and I’m using the Observer Pattern. The
cParamsContextwould be the observable in this case. I’m using a signal/slot / event/delegate implementation of the observer pattern. So far, it has worked wonders for my task.