c ++ behavioral patterns _ state (State)

1) intent

It allows an object to change its behavior when its internal state changes. The object will appear to change its class

2) structure

 

 

 among them:

  1. Context defines the interface of interest to clients, maintaining a ConcreteState instance of a subclass, the instance defines the current state
  2. State defining an interface to encapsulate the Context a specific state related behaviors
  3. ConcreteState each sub-class implementation with Context -related behavior of a state

3) Applicability

  1. Behavior of an object depends on its state, and it must change its behavior according to the state at run time
  2. Conditional statements contained in a large multi-operation branches, and these branches depend on the state of the object

4) Examples

 1 #include <iostream>
 2 #include <list>
 3 class State;
 4 class Context
 5 {
 6 public:
 7     Context(State* state):m_state(state) {}
 8     virtual ~Context() 
 9     {
10         if (m_state)
11         {
12             delete m_state;
13         }
14     }
15     void request();
16     void changeState(State* state)
17     {
18         if (m_state) delete m_state;
19         m_state = state;
20     }
21     void show();
22 private:
23     State* m_state;
24 };
25 class State
26 {
27 public:
28     State(){}
29     virtual ~State() {}
30     virtual void Handle(Context* pContext) = 0;
31     virtual void printState() = 0;
32 };
33 
34 class ConcreateStateA : public State
35 {
36 public:
37     ConcreateStateA() {}
38     virtual ~ConcreateStateA() {}
39     virtual void Handle(Context* pContext);
40     virtual void printState()
41     {
42         std::cout << "state is ConcreateStateA" << std::endl;
43     }
44 };
45 class ConcreateStateB : public State
46 {
47 public:
48     ConcreateStateB() {}
49     virtual ~ConcreateStateB() {}
50     virtual void Handle(Context* pContext);
51     virtual void printState()
52     {
53         std::cout << "state is ConcreateStateB" << std::endl;
54     }
55 };
56 void Context::request()
57 {
58     m_state->Handle(this);
59 }
60 void Context::show()
61 {
62     m_state->printState();
63 }
64 void ConcreateStateA::Handle(Context* pContext)
65 {
66     pContext->changeState(new ConcreateStateB());
67 }
68 void ConcreateStateB::Handle(Context* pContext)
69 {
70     pContext->changeState(new ConcreateStateA());
71 }
72 int main() 
73 {
74     State* pStateA = new ConcreateStateA();
75     Context* pContext = new Context(pStateA);
76     pContext->show();
77 
78     pContext->request();
79     pContext->show();
80 
81     pContext->request();
82     pContext->show();
83 
84     pContext->request();
85     pContext->show();
86 
87     delete pContext;
88     system("pause");
89 }

 

Guess you like

Origin www.cnblogs.com/ho966/p/12239175.html