状态模式(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

相关文章
相关标签/搜索