【行为型】状态模式
定义
1
2
3
4
5
6
定义:当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
命令模式中角色:
1.抽象状态类(AbstractState): 将具体状态类行为定义一个抽象方法
2.具体状态类(ConcreteState): 继续抽象状态类,实现具体的行为
3.容器类(Context): 存储具体状态类
UML图
1
2
3
4
5
6
7
8
9
10
11
12
_ _ _ _ _ _ _ _ _ _ _ _ _
| | | |
| Context |---→| AbstractState |
|_ _ _ _ _| |_ _ _ _ _ _ _ _|
↑
___________|__________
| |
| |
_ _ _ _|_ _ _ _ _ _ _ _|_ _ _ _
| | | |
| ConcreteStateA| | ConcreteStateB|
|_ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _|
代码
1
2
3
4
public abstract class TripState{
public abstract void handle(Context context);
}
1
2
3
4
5
6
7
8
9
10
public class DriverArrive extends TripState{
public void handle(Context context){
System.out.println("The driver have arrived and notice the guest. Waiting...");
context.setTripState( new StartTrip() );
}
}
1
2
3
4
5
6
7
public class StartTrip extends TripState{
public void handle(Context context){
System.out.println("The guests are ready! Go with perfect day.");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Context{
private TripState tripState;
public Context(TripState tripState){
this.tripState = tripState;
}
//Getter And Setter
...
public void request(){
tripState.handle(this);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Client{
public static void main(String[] args){
Context trip = new Context( new DriverArrive() );
trip.request();
trip.request();
}
}
运行结果:
The driver have arrived and notice the guest. Waiting...
The guests are ready! Go with perfect day.