状态模式

2016-05-21  本文已影响32人  keith666

Intent

Structure

state by keith
  1. 代码:
public class State {
    public static void main(String[] args) {
        State state = new State();
        state.test();
    }

    private void test() {
        Context context = new Context();
        context.request();
        context.request();
    }

    class Context {
        BaseState state;

        public Context() {
            this.state = new StartState(this);
        }
        public void setState(BaseState state){
            this.state=state;
        }
        public void request() {
            state.handle();
        }
    }
    // base state
    interface BaseState {
        void handle();
    }
    // change the state internally
    class StartState implements BaseState {

        Context context;

        public StartState(Context context) {
            this.context = context;
        }

        @Override
        public void handle() {
            System.out.println("start it.");
            context.setState(new StopState());
        }
    }
    class StopState implements BaseState {

        @Override
            public void handle() {
            System.out.println("stop it.");
        }
    }
}
  1. Output
start it.
stop it.

Notice:

Refenrence

  1. Design Patterns
  2. 设计模式
  3. 状态模式和策略模式的相似与不同
上一篇下一篇

猜你喜欢

热点阅读