状态模式

状态模式(State):当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了一个类

Class Diagram

Implementation

状态接口

1
2
3
4
5
public abstract class State {
protected String desc;
public abstract void handle(Context context);
public abstract void display();
}

具体状态

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
public class ConcreteStateA extends State {

{
desc = "休息中";
}

@Override
public void handle(Context context) {
System.out.println("当前状态" + desc);
System.out.println("状态处理,切换工作状态");
context.setState(new ConcreteStateB());
}

@Override
public void display() {
System.out.println("状态:" + desc);
}
}

public class ConcreteStateB extends State {

{
desc = "工作中";
}

@Override
public void handle(Context context) {
System.out.println("当前状态" + desc);
System.out.println("状态处理,切换工作状态");
context.setState(new ConcreteStateA());
}

@Override
public void display() {
System.out.println("状态:" + desc);
}
}

使用状态的实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Context {
private State state;

public Context(State state) {
this.state = state;
}

public State getState() {
return state;
}

public void setState(State state) {
this.state = state;
}

public void request(){
state.handle(this);
}

public void displayState(){
state.display();
}
}

测试类

1
2
3
4
5
6
7
8
9
10
11
public class StateTest {
@Test
public void test() throws Exception {
Context context = new Context(new ConcreteStateA());
context.displayState();
context.request();
context.displayState();
context.request();
context.displayState();
}
}

Example

Reflence