设计模式笔记:状态模式

状态模式:当状态改变会改变行为时,将状态与行为封装到一个类中。

在状态发生改变时对应的处理方法也发生改变,允许一个对象在其内部改变时改变它的行为。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//头文件
#include <iostream>
using namespace std;
class Context;//声明
//抽象出来的状态类
class State
{
public:
/*抽象的接口,每个子类去实现这个接口
根据自己的逻辑执行任务或者转换状态。
*/
virtual void Handle(Context *context) = 0;
//获得当前的状态
virtual void GetState() = 0;
};
//状态管理类
class Context
{
public:
//初始化状态
Context(State *state)
{
m_pState = state;
}
//获得当前的状态
State* GetState()
{
return m_pState;
}
//改变当前的状态
void SetState(State *state)
{
m_pState = state;
}
//执行状态类实现的方法
void Request()
{
m_pState->Handle(this);
}
State* m_pState;
};
//具体的状态子类
class ConcreteStateA:public State
{
public:
void Handle(Context *context);
void GetState();
};
//具体的状态子类
class ConcreteStateB:public State
{
public:
void Handle(Context *context);
void GetState();
};
//具体的状态子类
class ConcreteStateC:public State
{
public:
void Handle(Context *context);
void GetState();
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//cpp文件
#include "StateMode.h"
void ConcreteStateA:: Handle(Context *context)
{
context->m_pState = new ConcreteStateB;
cout<<"当前状态是A,下一状态是B"<<endl;
}
void ConcreteStateB:: Handle(Context *context)
{
context->m_pState = new ConcreteStateC;
cout<<"当前状态是B,下一状态是C"<<endl;
}
void ConcreteStateC:: Handle(Context *context)
{
context->m_pState = new ConcreteStateA;
cout<<"当前状态是C,下一状态是A"<<endl;
}
void ConcreteStateA:: GetState()
{
cout<<"当前状态是A"<<endl;
}
void ConcreteStateB:: GetState()
{
cout<<"当前状态是B"<<endl;
}
void ConcreteStateC:: GetState()
{
cout<<"当前状态是B"<<endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
//main函数
#include "StateMode.h"
int main(void)
{
//初始化A状态
Context* context = new Context(new ConcreteStateA);
context->Request();
context->Request();
context->Request();
getchar();
return 0;
}