A typical scenario of state pattern involves states which are mostly different like closed_connection_state
or open_connection_state
. In my case, all the states are essentially the same but the operation needs to apply to the currently selected object.
Typically something like this is done using an index variable which points to the currently selected object but is using state pattern a better implementation to do this like in the example below?
class Object
{
std::string _name;
public:
Object(std::string name) : _name(name)
{
}
void Perform()
{
std::cout << _name << " Perform called\r\n";
}
};
class CurrentObject
{
Object* _a;
Object* _b;
Object* _current;
public:
CurrentObject(Object* a, Object* b) : _a(a), _b(b)
{
_current = a;
}
void Perform()
{
_current->Perform();
// Update _current logic goes here, lets just switch
// the state whenever `Perform` is called.
if (_current == _a)
_current = _b;
else
_current = _a;
};
};
int main()
{
Object a("a");
Object b("b");
CurrentObject current(&a, &b);
// assume Perform() does something and it may does may also change
// the currently selected object. In this example, it always change it.
current.Perform();
current.Perform();
current.Perform();
}
Aucun commentaire:
Enregistrer un commentaire