狀態模式(State)

狀態模式git

一. 狀態模式

1.1 定義

  • 容許一個對象在其內部狀態改變時改變它的行爲.這個對象看起來像是改變了其類.

二. 具體實現

2.1 建立抽象狀態接口

public interface IState {
        void print(Context context);
    }

2.2 建立容器

public class Context {
        private IState state;
        public Context(){
            this.state = null;
        }
        public void setState(IState state){
            this.state = state;
            System.out.println("setState : " + state.getClass().getSimpleName());
        }
        public void print(){
            state.print(this);
        }
    }

2.3 建立具體狀態類

public class StateA implements IState {
        @Override
        public void print(Context context) {
            System.out.println("StateA print ...");
            context.setState(new StateB());
        }
    }
    public class StateB implements IState {
        @Override
        public void print(Context context) {
            System.out.println("StateB print ...");
            context.setState(new StateA());
        }
    }

2.5 調用

public static void main(String[] args) {
        Context context = new Context();
        context.setState(new StateA());
        context.print();
        context.print();
    }

2.6 輸出

setState : StateA
    StateA print ...
    setState : StateB
    StateB print ...
    setState : StateA

三. 優缺點

3.1 優勢

  • 封裝了轉換規則.
  • 擴展性強,易於添加新的狀態對象或行爲.

3.2 缺點

  • 狀態過多致使類膨脹.

四. 源碼

https://github.com/Seasons20/DisignPattern.git

ENDgithub

相關文章
相關標籤/搜索