0%

状态模式

描述

状态模式就两点:1、可以通过改变状态来获得不同的行为。2、你的好友能同时看到你的变化。

思想

当对象的状态改变时,同时改变其行为

适用

状态模式在日常开发中用的挺多的,尤其是做网站的时候,我们有时希望根据对象的某一属性,区别开他们的一些功能,比如说简单的权限控制

UML

42847310f43a4ac0a8bf7927c6185d94

示例

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
//状态类的核心类
class State{
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public void name(){
Test.printMsg("State.name");
}
public void say(){
Test.printMsg("State.say");
}
}
//状态模式的切换类
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 method() {
if (state.getValue().equals("name")) {
state.name();
} else if (state.getValue().equals("say")) {
state.say();
}
}
}
//测试
public class Test {
public static void printMsg(String msg){
System.out.println(msg);
}
public static void main(String[] args){
State state = new State();
Context context = new Context(state);
//设置第1种状态
state.setValue("name");
context.method();
//设置第2种状态
state.setValue("say");
context.method();
}
}