设计模式学习之五-状态模式

状态模式应用场景

这个模式在工作中也比较常见,就是点击按钮,根据按钮目前的状态来决定所要执行的操作,2个状态的比如开关按钮。我们普遍会拿if来做判断。但是状态比较多的情况下,多个if就比较low了。于是就应用到了状态模式

状态模式应用案例

比如我们在按灯泡开关的时候,灯泡的状态分为关灯,弱光,强光,超强光。

先上代码:

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
var OffLightState = function(light){
this.light = light;
}

OffLightState.prototype.buttonWasPressed = function(){
console.log('弱光');
this.light.setState(this.light.weakLightState);
}

var WeakLightState = function(light){
this.light = light;
}

WeakLightState.prototype.buttonWasPressed = function(){
console.log('强光');
this.light.setState(this.light.strongLightState);
}


var StrongLightState = function(light){
this.light = light;
}

StrongLightState.prototype.buttonWasPressed = function(){
console.log('超强光');
this.light.setState(this.light.superstrongLightState);
}

var SuperStrongLightState = function(light){
this.light = light;
}

SuperStrongLightState.prototype.buttonWasPressed = function(){
console.log('关灯');
this.light.setState(this.light.offLightState);
}


var Light = function(){
this.offLightState = new OffLightState(this);
this.weakLightState = new WeakLightState(this);
this.strongLightState = new StrongLightState(this);
this.superstrongLightState = new SuperStrongLightState(this);
this.button = null;
}

Light.prototype.init = function(){
var button = document.createElement('button'),
_self = this;

this.button = document.body.appendChild(button);
this.button.innerHTML = '开关';

this.currState = this.offLightState;

this.button.onclick = function(){
_self.currState.buttonWasPressed();
}
}

Light.prototype.setState = function(newState){
this.currState = newState;
}

var light = new Light();
light.init();

这段代码的核心思想就是为每个状态创建个对象,然后每个状态对象里都声明一个buttonWasPressed点击按钮方法,重要的是每个状态里都要显式的写出当前状态的下一个状态,然后切换到下一个状态,这样每次点击按钮,其实触发的是不同状态对象里的buttonWasPressed方法。

(完)