什么是状态模式

在状态模式(State Pattern)中,类的行为是基于它的状态改变的。这种类型的设计模式属于行为型模式。

在状态模式中,我们创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象。

面向对象例子:

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class BasicState{
constructor(control) {
this.control = control;
}

btnWasPressed(dom) {
throw new Error('Basic function must be rewrite');
}

stopWasPressed(dom) {
throw new Error('Basic function must be rewrite');
}
}

class StopState extends BasicState{
constructor(control) {
super(control);
}

btnWasPressed(dom) {
console.log('starting play');
dom.innerText = 'pause';
this.control.setState(this.control.playState);
}

stopWasPressed(dom) {
console.log('stoped');
dom.innerText = 'start';
this.control.setState(this.control.stopState);
}
}

class PlayState extends BasicState{
constructor(control) {
super(control);
}

btnWasPressed(dom) {
console.log('paused');
dom.innerText = 'start';
this.control.setState(this.control.pauseState);
}

stopWasPressed(dom) {
console.log('stoped');
dom.innerText = 'start';
this.control.setState(this.control.stopState);
}
}



class PauseState extends BasicState{
constructor(control) {
super(control);
}

btnWasPressed(dom) {
console.log('starting play');
dom.innerText = 'pause';
this.control.setState(this.control.playState);
}

stopWasPressed(dom) {
console.log('stoped');
dom.innerText = 'start';
this.control.setState(this.control.stopState);
}
}



export default class Control{
constructor() {
this.stopState = new StopState(this);
this.playState = new PlayState(this);
this.pauseState = new PauseState(this);
this.currentState = this.stopState;
}

setState(state) {
this.currentState = state;
}
}