In the state template, you represent the state of an object using state objects. These state objects represent a certain state, but they do not have any mutable state. This means that they never change. Therefore, any number of objects can simultaneously use the same state object (even from different threads). If the state-object has a mutable state, other objects will have to worry about changing their state object from another place.
The use of one instance of an object by many others can be considered as an instance of flyweight-pattern .
, :
class SomeStateMachine;
class AbstractState {
void input(const std::string & data, SomeStateMachine & caller) = 0;
}
class FinalState : public AbstractState {
FinalState * getInstance();
}
class InitialState : public AbstractState {
public:
InitialState * getInstance();
void input(const std::string & data, SomeStateMachine & caller) {
std::cout << data << std::endl;
caller.m_State = FinalState::getInstance();
}
}
class SomeStateMachine {
public:
SomeStateMachine() : m_State(InitialState::getInstance())
void input(const std::string & data) {
m_State->input(data, *this);
}
private:
friend class InitialState;
AbstractState * m_State;
};
, state. , , . , , .