Problems with the implementation of state problems of the state GOF

First, can anyone explain how a state object can be split if the state object has no instance variables?

This text is taken from GOF, p. 308, paragraph 3 (impact section):

The state object can be shared. If state objects do not have a variabkes instance, that is, the state they represent is fully encoded type - then contexts can state objects. When states are divided in this way, they are essentially the easiest.

Can anyone explain this text?

Secondly, what are the approaches to the decision on state transition? I mean the decision about which next state will be distributed?

Please, help. Thank you

+3
source share
2 answers

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 {
    // abstract baseclass for all state-classes
    void input(const std::string & data, SomeStateMachine & caller) = 0;
}

class FinalState : public AbstractState {
    FinalState * getInstance(); // always returns same instance
}

class InitialState : public AbstractState {
public:
    InitialState * getInstance(); // always returns same instance
    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. , , . , , .

+2

, - - "", , .

, : "", "" "". :

abstract class State {};

class Open extends State {

  public Open() {}

}

class Active extends State {

  public Active() {}

}

class Closed extends State {

  public Closed() {}

}

-

- , , GOF, , ( ), -

public class State {

  private string name;

  private State(String name) {
    this.name = name;
  }

  public final static State OPEN = new State("Open");
  public final static State ACTIVE = new State("Active");
  public final static State CLOSED = new State("Closed");

}

, , . ( !) , , , . . " " (ISBN: 0321213351)

EDIT (2): - - http://www.industriallogic.com/xp/refactoring/alteringConditionalsWithState.html

alt text

+2

Source: https://habr.com/ru/post/1752794/


All Articles