一、引出状态模式
假设我们此刻有一个糖果机项目,那么我们知道正常一般糖果机提供应用户的行为有这么几种:投入硬币、动弹曲柄、退出硬币几种行为;那么糖果机呢一般有这几中状态,待机状态、持有硬币的筹备状态、运行状态即正在售出状态和初始状态 这么几种正常状态。 我们发明处于差异状态的时候,持有的行为是纷歧样的,图如下:
假如我们回收传统的要领来写代码,那么在投入硬币这个行为操纵的时候,我们会举办状态的判定,只有在处于待机状态环境下这种行为是正常的,而其他则非正常,那么其他行为也一样,都需要去先判定下当前的状态来举办操纵。获得的代码则为:
package study.designmode.statemode; public class CandyMachine { final static int SoldOutState = 0; //初始状态 final static int OnReadyState = 1; //待机状态 final static int HasCoin = 2; //筹备状态 final static int SoldState = 3; //售出状态 private int state = SoldOutState; //变量,用于存放当前的状态值 private int count = 0; //糖果的数目 public CandyMachine(int count) { this.count = count; if (count > 0) { state = OnReadyState; } } //投入硬币行为的时候,通过判定当前的状态来匹配所有的状态. public void insertCoin() { switch (state) { case SoldOutState: System.out.println("you can't insert coin,the machine sold out!"); break; case OnReadyState: //只有在待机状态的时候,投入硬币行为正确,并将状态改变为筹备状态 state = HasCoin; System.out .println("you have inserted a coin,next,please turn crank!"); break; case HasCoin: System.out.println("you can't insert another coin!"); break; case SoldState: System.out.println("please wait!we are giving you a candy!"); break; } } //回退硬币 public void returnCoin() { switch (state) { case SoldOutState: System.out .println("you can't return,you haven't inserted a coin yet!"); break; case OnReadyState: System.out.println("you haven't inserted a coin yet!"); break; case HasCoin: System.out.println("coin return!"); state = OnReadyState; break; case SoldState: System.out.println("sorry,you already have turned the crank!"); break; } } //动弹曲柄 public void turnCrank() { switch (state) { case SoldOutState: System.out.println("you turned,but there are no candies!"); break; case OnReadyState: System.out.println("you turned,but you haven't inserted a coin!"); break; case HasCoin: System.out.println("crank turn...!"); state = SoldState; dispense(); break; case SoldState: System.out .println("we are giving you a candy,turning another get nothing,!"); break; } } //触发发放糖果行为 private void dispense() { count = count - 1; System.out.println("a candy rolling out!"); if (count > 0) { state = OnReadyState; } else { System.out.println("Oo,out of candies"); state = SoldOutState; } } public void printstate() { switch (state) { case SoldOutState: System.out.println("***SoldOutState***"); break; case OnReadyState: System.out.println("***OnReadyState***"); break; case HasCoin: System.out.println("***HasCoin***"); break; case SoldState: System.out.println("***SoldState***"); break; } } }
那么上面这种方法存在什么问题呢?首先很直观的感觉就是:
1.存在大量的switch case 语句 虽然可以用if else 也是一样的。
2.可扩展性差,而且一旦要插手一种新的状态,那么就会要修改所有的switch case 不切合开闭原则
3.没有回收面向工具的方法去封装
好比,这个时候,新增加了一种状态,赢家状态,即可以获取到两粒糖果;那么假如用上面的方法,必定是不切合开闭原则的,同时扩展性也是欠好的;那么我们有什么其它的方法来办理呢?
二、办理步伐