State Pattern

State pattern, 状态模式,是一种对象行为模式。又称状态对象(Objects for States).

【意图】允许一个对象在其内部状态改变时改变其行为。对象看起来像是改变了它的类。

【类图】如下所示:

state pattern

【代码】部分代码如下,全部代码可以在 http://code.google.com/p/cyiridiumsitewikineed/source/browse/trunk/src/designpattern/org/iridium/dp/state 查看。

public interface State {
    void oper1();
    void oper2();
}
public class ConcreteStateA implements State {
    @Override
    public void oper1() {
        System.out.println("state a, oper1");
    }
    @Override
    public void oper2() {
        System.out.println("state a, oper2");
    }
}
public class ConcreteStateB implements State {
    @Override
    public void oper1() {
        System.out.println("state b, oper1");
    }
    @Override
    public void oper2() {
        System.out.println("state b, oper2");
    }
}
public class Context {
    private State state;
    public void oper1() {
        state.oper1();
    }
    public void oper2() {
        state.oper2();
    }
    public State getState() {
        return state;
    }
    public void setState(State state) {
        this.state = state;
    }
}
public class Client {
    public static void main(String[] args) {
        Context contex = new Context();
        State stateA = new ConcreteStateA();
        contex.setState(stateA);
        contex.oper1();
        contex.oper2();
        State stateB = new ConcreteStateB();
        contex.setState(stateB);
        contex.oper1();
        contex.oper2();
    }
}

以上代码,执行 Client.main 后,输出如下内容:

state a, oper1
state a, oper2
state b, oper1
state b, oper2