- 定义
允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它的类。 - 说明
将状态封装成为独立的类,并将动作委托到代表当前状态的对象。 代码实例
/** * 场景描述:开关电脑状态机。当关闭状态时,按下按钮到开启状态。当开启状态时,按下按钮到关闭状态。 */ /** * 状态封装动作行为 */ 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(); } }
来源:https://www.cnblogs.com/bosslv/p/11356385.html