Java的State模式

 State模式:

    允许一个对象在其状态改变时,改变它的行为。看起来对象似乎修改了它的类。

    例子:

 

    view plaincopy to clipboardprint?
    public interface State {
        public void handle(Context ctx);
    }

    public class Context {

        private State _state;

        public Context(State state) {
            _state = state;
        }

        public void request() {
            if (_state != null) {
                _state.handle(this);
            }
        }

        public void ChangeState(State s) {
            if (_state != null) {
                _state = null;
            }
            _state = s;
        }
    }

    public class ConcreteStateA implements State {

        public void handle(Context ctx) {
            System.out.println("handle by ConcreteStateA");
            if (ctx != null) {
                ctx.ChangeState(new ConcreteStateB());
            }
        }
    }

    public class ConcreteStateB implements State {

        public void handle(Context ctx) {
            System.out.println("handle by ConcreteStateB");
            if (ctx != null) {
                ctx.ChangeState(new ConcreteStateA());
            }
        }
    }

    public class StateClient {

        public static void main(String[] args) {

            State state = new ConcreteStateA();
            Context context = new Context(state);
            context.request();
            context.request();
            context.request();
            context.request();
        }
    }
 

Copyright ?2005-2008 All rights reserved. www.17zixue8.com 版权所有    赣ICP备07501614号        完美兵团会员待遇说明    站主QQ:335759285