概述
- 定义:允许一个对象在其内部状态改变的时候改变其行为。这个对象看上去就像是改变了它的类一样
- 适用场景:
- 一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为
- 一个操作中含有庞大的多分支结构,并且这些分支决定于对象的状态
实现
// 状态接口
public interface State {
void handle(String param);
}
class ConcreteStateA implements State {
private Context c;
public ConcreteStateA(Context c) {
this.c = c;
}
@Override
public void handle(String param) {
System.out.println("ConcreteStateA is handleing " + param);
c.setState(new ConcreteStateB(c));
}
}
class ConcreteStateB implements State {
private Context c;
public ConcreteStateB(Context c) {
this.c = c;
}
@Override
public void handle(String param) {
System.out.println("ConcreteStateB is handleing " + param);
c.setState(new ConcreteStateA(c));
}
}
// 环境角色类
public class Context {
private State state;
public void setState(State state) {
this.state = state;
}
public void doSomething(String param) {
state.handle(param);
}
}
// 客户端
public class Client {
public static void main(String[] args) throws Exception {
Context c = new Context();
State s = new ConcreteStateA(c);
c.setState(s);
c.doSomething("aaa");
c.doSomething("aaa");
c.doSomething("aaa");
c.doSomething("aaa");
}
}
输出结果
ConcreteStateA is handleing aaa
ConcreteStateB is handleing aaa
ConcreteStateA is handleing aaa
ConcreteStateB is handleing aaa
与策略模式的区别
策略模式:封装一系列平行且复杂多变的实现方式
状态模式:实现把对象的内在状态的变化封装起来,用外部行为来表现出来