标签:oid 定义 开启 ret etc 设计模式 改变 this 独立
代码实例
/**
* 场景描述:开关电脑状态机。当关闭状态时,按下按钮到开启状态。当开启状态时,按下按钮到关闭状态。
*/
/**
* 状态封装动作行为
*/
interface State {
void press();
}
/**
* 开启状态下的行为
*/
class OpenState implements State {
private Computer computer;
public OpenState(Computer computer) {
this.computer = computer;
}
@Override
public void press() {
System.out.println("关闭电脑");
computer.setCurrentState(computer.getCloseState());
}
}
/**
* 关闭状态下的行为
*/
class CloseState implements State {
private Computer computer;
public CloseState(Computer computer) {
this.computer = computer;
}
@Override
public void press() {
System.out.println("打开电脑");
computer.setCurrentState(computer.getOpenState());
}
}
class Computer{
private State openState;
private State closeState;
private State currentState;
public Computer() {
openState = new OpenState(this);
closeState = new CloseState(this);
currentState = closeState;
}
public void press() {
currentState.press();
}
/* 以下为辅助方法 */
public void setCurrentState(State currentState) {
this.currentState = currentState;
}
public State getCloseState() {
return closeState;
}
public State getOpenState() {
return openState;
}
// 测试
public static void main(String[] args) {
Computer computer = new Computer();
computer.press();
computer.press();
computer.press();
computer.press();
}
}
标签:oid 定义 开启 ret etc 设计模式 改变 this 独立
原文地址:https://www.cnblogs.com/bosslv/p/11356385.html