状态模式
image20250314213512510.png

允许对象在其内部状态改变时改变其行为。状态模式可以避免多个条件语句的使用,并使得状态行为更加清晰。

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
63
64
// 状态基类
class State {
public:
virtual void handle() = 0; // 不同状态实现,体现不同状态下的行为
~State() {
cout << "~State()" << endl;
}
};


// 具体状态

class RedLight : public State {
public:
void handle() override {
cout << "Red Light : Stop" << endl;
}

~RedLight() {
cout << "~RedLight()" << endl;
}
};

class GreenLight : public State {
public:
void handle() override {
cout << "Green Light : Walk" << endl;
}

~GreenLight() {
cout << "~GreenLight()" << endl;
}
};

class YellowLight : public State {
public:
void handle() override {
cout << "Yellow Light : Wait" << endl;
}

~YellowLight() {
cout << "~YellowLight()" << endl;
}
};

// 管理状态的上下文
// 根据不同的状态,产生不同的行为

class TrafficLight {
public:
explicit TrafficLight(shared_ptr<State> state)
: state_(state) {}

void setState(shared_ptr<State> state) {
state_ = state;
}

void request() {
state_->handle();
}

private:
shared_ptr<State> state_;
};

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main() {

// 创建三个不同状态的对象

shared_ptr<State> redLight = make_shared<RedLight>();
shared_ptr<State> greenLight = make_shared<GreenLight>();
shared_ptr<State> yellowLight = make_shared<YellowLight>();

// 创建驱使状态行为的上下文
shared_ptr<TrafficLight> traffic_light = make_shared<TrafficLight>(redLight);
traffic_light->request();

cout << " 60s ,red --> green" << endl;
traffic_light->setState(greenLight);
traffic_light->request();

cout << " 3s ,green --> yellow" << endl;
traffic_light->setState(yellowLight);
traffic_light->request();

return 0;
}

基于条件语句的状态机会暴露其最大的弱点。 为了能根据当前状态选择完成相应行为的方法, 绝大部分方法中会包含复杂的条件语句。 修改其转换逻辑可能会涉及到修改所有方法中的状态条件语句, 导致代码的维护工作非常艰难。

通过状态模式,如果后续有新的状态出现,我们不需要对已有状态派生类进行改动(即入侵代码),只需要新建状态派生类并重写方法即可。

image20250314210923939.png