概念
- 状态模式属于行为型模式;
- 只需要改变对象状态即可改变对象的行为;
- 状态模式对"开闭原则"的支持并不太好;所以对象状态最好为有限个且不常变动;
- 场景:
- 1、行为随状态、属性改变而改变的场景。
- 2、条件、分支语句的代替者。
3个角色
- State:抽象状态角色;负责对象状态定义, 并且封装环境角色以实现状态切换。
- ConcreteState:具体状态角色;每一个具体状态必须完成两个职责:本状态下要做的事情, 以及本状态如何过渡到其他状态。
- Context:环境角色:定义客户端调用的接口, 并且负责具体状态的切换;
- 环境角色有两个不成文的约束:
- 1、把状态对象声明为静态常量, 有几个状态对象就声明几个静态常量;
- 2、环境角色具有状态抽象角色定义的所有行为, 具体执行使用委托方式;
demo
package com.cn.go.designpattern;
public class State {
public static void main(String[] args) {
Context context = new Context();
context.setCurrentState(Context.WAKE_UP);
context.wakeUp();
context.work();
context.sleep();
}
}
abstract class AbstractState {
Context context;
public void setContext(Context context) {
this.context = context;
}
abstract void wakeUp();
abstract void sleep();
abstract void work();
}
class WakeUp extends AbstractState {
void wakeUp() {
System.out.println("wake_up");
}
void sleep() {
super.context.setCurrentState(Context.SLEEP);
super.context.getCurrentState().sleep();
}
void work() {
super.context.setCurrentState(Context.WORK);
super.context.getCurrentState().work();
}
}
class Sleep extends AbstractState {
void wakeUp() {
super.context.setCurrentState(Context.WAKE_UP);
super.context.getCurrentState().sleep();
}
void sleep() {
System.out.println("hu hu ....");
}
void work() {
}
}
class Work extends AbstractState {
void wakeUp() {
}
void sleep() {
super.context.setCurrentState(Context.SLEEP);
super.context.getCurrentState().sleep();
}
void work() {
System.out.println("brick-carrying , ctrl-c, ctrl-v");
}
}
class Context {
public final static WakeUp WAKE_UP = new WakeUp();
public final static Sleep SLEEP = new Sleep();
public final static Work WORK = new Work();
public AbstractState getCurrentState() {
return currentState;
}
private AbstractState currentState;
public void setCurrentState(AbstractState currentState) {
this.currentState = currentState;
this.currentState.setContext(this);
}
void wakeUp() {
this.currentState.wakeUp();
}
void sleep() {
this.currentState.sleep();
}
void work() {
this.currentState.work();
}
}