熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java設計模式-----State模式

2022-06-13   來源: Java核心技術 

  源自

  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) {
                _statehandle(this);
            }
        }

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

  public class ConcreteStateA implements State {

  public void handle(Context ctx) {
            Systemoutprintln(handle by ConcreteStateA);
            if (ctx != null) {
                ctxChangeState(new ConcreteStateB());
            }
        }
    }

  public class ConcreteStateB implements State {

  public void handle(Context ctx) {
            Systemoutprintln(handle by ConcreteStateB);
            if (ctx != null) {
                ctxChangeState(new ConcreteStateA());
            }
        }
    }

  public class StateClient {

  public static void main(String[] args) {

  State state = new ConcreteStateA();
            Context context = new Context(state);
            contextrequest();
            contextrequest();
            contextrequest();
            contextrequest();
        }
    }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/25974.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.