文章目录
  1. 状态模式

状态模式

  • 允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。
    State
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
public interface PhoneState {
void handle(Phone phone);
}
public class NormalState implements PhoneState {
@Override
public void handle(Phone phone) {
System.out.println("系统关机");
phone.setPhoneState(new ShutdownState());
}
}
public class ShutdownState implements PhoneState {
@Override
public void handle(Phone phone) {
System.out.println("系统开机");
phone.setPhoneState(new NormalState());
}
}
public class Phone {
private PhoneState phoneState;
public Phone(){
this.phoneState=new ShutdownState();
}
public void clickButton(){
phoneState.handle(this);
}
public void setPhoneState(PhoneState phoneState) {
System.out.println("状态改变:"+phoneState.toString());
this.phoneState = phoneState;
}
}
public class App {
public static void main(String[] args) {
Phone phone=new Phone();
phone.clickButton();
phone.clickButton();
}
}
文章目录
  1. 状态模式