状态模式(State)主要是为了在运行时改变记录状态。

关于状态模式的故事

人们可以根据不同的财务生活。他们可以是富有或者是平穷。这是两种状态”富裕”和”平穷”,根据时间的流逝这个是状态是可以改变的。这个例子的想法是:通常平穷的人们都在非常努力的工作而富裕的人都在玩。他们做什么取决于他们的状态。状态可以改变他们的行为,否则,社会太不公平了。(努力可以改变平穷,富裕贪玩也能变成平穷)

状态模式类图

这是一个类图。你可以和策略模式)对比这理解,这样你可以更好的理解他们的不同。

 Arrayin Memory

状态模式的java实现

下面的java代码展示了状态模式的工作方式。

State 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.programcreek.designpatterns.state;
interface State {
public void saySomething(StateContext sc);
}
class Rich implements State{
@Override
public void saySomething(StateContext sc) {
System.out.println("I'm rick currently, and play a lot.");
sc.changeState(new Poor());
}
}
class Poor implements State{
@Override
public void saySomething(StateContext sc) {
System.out.println("I'm poor currently, and spend much time working.");
sc.changeState(new Rich());
}
}

StateContext 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.programcreek.designpatterns.state;
public class StateContext {
private State currentState;
public StateContext(){
currentState = new Poor();
}
public void changeState(State newState){
this.currentState = newState;
}
public void saySomething(){
this.currentState.saySomething(this);
}
}

测试Main 类

1
2
3
4
5
6
7
8
9
10
11
import com.programcreek.designpatterns.*;
public class Main {
public static void main(String args[]){
StateContext sc = new StateContext();
sc.saySomething();
sc.saySomething();
sc.saySomething();
sc.saySomething();
}
}

结果:

I'm poor currently, and spend much time working. 
I'm rick currently, and play a lot.
I'm poor currently, and spend much time working. 
I'm rick currently, and play a lot.

参考文档