1.每个人、事物在不同的状态下会有不同表现(动作),而一个状态又会在不同的表现下转移到下一个不同的状态(State).State Pattern 将每一个分支都封装到独立的类中,将状态逻辑和动作实现进行分离。提高了系统的扩展性和可维护性。

2.State Pattern结构图

State Pattern

3.实现:如果代码看的不懂,可以运行main()代码单步跟踪就明白了。

 1 #ifndef _STATE_H_ 
 2 #define _STATE_H_
 3 
 4 class Context; //前置声明
 5 class State 
 6 {
 7 public: 
 8     State();
 9     virtual ~State();
10     virtual void OperationInterface(Context* ) = 0;
11     virtual void OperationChangeState(Context*) = 0;
12 protected: 
13     bool ChangeState(Context* con,State* st);
14 private: 
15     //bool ChangeState(Context* con,State* st);
16 };
17 
18 class ConcreteStateA:public State 
19 {
20 public: 
21     ConcreteStateA();
22     virtual ~ConcreteStateA();
23     virtual void OperationInterface(Context* );
24     virtual void OperationChangeState(Context*);
25 protected:
26 private:
27 };
28 
29 class ConcreteStateB:public State 
30 { 
31 public:
32     ConcreteStateB();
33     virtual ~ConcreteStateB();
34     virtual void OperationInterface(Context* );
35     virtual void OperationChangeState(Context*);
36 protected:
37 private:
38 }; 
39 
40 #endif
State.h

相关文章:

  • 2021-11-27
  • 2021-12-24
  • 2021-10-22
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-10
  • 2021-08-04
  • 2021-10-24
  • 2021-11-25
  • 2021-09-24
  • 2021-06-18
相关资源
相似解决方案