定义
当一个对象内在状态改变时允许其改变行为,这个对象看起来像是改变了其类。
类型
创建类模式
类图

要素
代码实现
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 53 54 55 56 57
| public abstract class State { protected Context context;
public void setContext(Context _context){ this.context = _context; }
public abstract void handle1();
public abstract void handle2(); }
public class ConcreteState1 extends State { @Override public void handle1(){ super.context.setCurrectState(Context.STATE2); super.context.handle2(); } @Override public void handle2(){
} }
public class Context{ public final static State STATE1 = new ConcreteState1(); public final static State STATE2 = new ConcreteState2();
private State CurrentState();
public State getCurrentState() { return CurrentState; }
public void setCurrentState(State currentState) { this.CurrentState = currentState; this.CurrentState.setContext(this); }
public void handle1(){ this.CurrentState.handle1(); }
public void handle2(){ this.CurrentState.handle2(); } }
public class Client { public static void main(String[] args){ Context context = new Context(); context.setCurrentState(new ConcreteState1);
context.handle1(); context.handle2(); } }
|
优点
结构清晰
避免许多switch…case
遵循设计原则
很好地体现了开闭原则和单一职责原则
- 封装性非常好
缺点
子类会太多,可以解决,比如在数据库中建立一个状态表,然后根据状态执行相应的操作。
使用场景
- 行为随状态改变而改变的场景
- 条件,分支判断语句的代替者