设计模式之状态模式(一)

时间:2019-07-23 14:59:00 来源:互联网 作者: 神秘的大神 字体:

我原本以为在对乡村的一切事物都很容易,但是每次我一回头就有更多变更的请求纷至沓来。我快崩溃了!----当小编读到这段话的时候,甚是感慨,设计模式的世界真的不是那么容易弄懂的,好在我还在学习。

基本常识:策略模式和状态模式是双胞胎,在出生时才分开。策略模式是围绕可以互换的算法来创建成功业务的。然而,状态走的是更崇高的路,它通过改变对象内部的状态来帮助对象控制自己的行为。

我们先来看下对象村的大家,这次又想出了什么。他们发现只要在糖果机里装上CPU,就可以增加销量、通过网络监测库存,并且能准确地得知客户的满意度。所有,就有了下面的这个设想:

状态机101

我们如何从状态图得到真正的代码呢?下面是一个实现状态机的简单介绍

  1. 首先,找出所有的状态:

我们有:没有25分钱、有25分钱、糖果售罄、售出糖果四个状态

  1. 接下来,创建一个实例变量来持有目前的状态,然后定义每个状态的值:
    final static int SOLD_OUT = 0;
    final static int NO_QUARTER = 1;
    final static int HAS_QUARTER = 2;
    final static int SOLD = 3;
 
    int state = SOLD_OUT;
  1. 现在,我们将所有系统中可以发生的动作整合起来:

投入25分钱、退回25分钱、转动曲柄、发放糖果

  1. 现在,我们创建一个类,它的作用就像是一个状态机。对每一个动作,我们都创建了一个对应的方法,这些方法利用条件语句来决定在每个状态内什么行为是恰当的。比如对“投入25分钱”这个动作来说,我们可以把对应方法写成下面的样子:
public void insertQuarter() {
    if (state == HAS_QUARTER) {
        System.out.println("You can't insert another quarter");
    } else if (state == NO_QUARTER) {
        state = HAS_QUARTER;
        System.out.println("You inserted a quarter");
    } else if (state == SOLD_OUT) {
        System.out.println("You can't insert a quarter, the machine is old out");
    } else if (state == SOLD) {
        System.out.println("Please wait, we're already giving you a gumball");
    }
}

写下代码

现在我们来实现糖果机。我们知道要利用实例变量持有当前的状态,然后需要处理所有可能发生的动作、行为和状态的转换。我们需要实现的动过包括:投入25分钱、退回25分钱、转动曲柄和发放糖果;也要检查糖果是否售罄。

public class GumballMachine {
 
    final static int SOLD_OUT = 0;
    final static int NO_QUARTER = 1;
    final static int HAS_QUARTER = 2;
    final static int SOLD = 3;
 
    int state = SOLD_OUT;
    int count = 0;
  
    public GumballMachine(int count) {
        this.count = count;
        if (count > 0) {
            state = NO_QUARTER;
        }
    }
    // 当有25分钱投进来,就会执行这里
    public void insertQuarter() {
        if (state == HAS_QUARTER) {
            System.out.println("You can't insert another quarter");
        } else if (state == NO_QUARTER) {
            state = HAS_QUARTER;
            System.out.println("You inserted a quarter");
        } else if (state == SOLD_OUT) {
            System.out.println("You can't insert a quarter, the machine is sold out");
        } else if (state == SOLD) {
            System.out.println("Please wait, we're already giving you a gumball");
        }
    }

    // 现在,如果顾客试着退回25分钱
    public void ejectQuarter() {
        if (state == HAS_QUARTER) {
            System.out.println("Quarter returned");
            state = NO_QUARTER;
        } else if (state == NO_QUARTER) {
            System.out.println("You haven't inserted a quarter");
        } else if (state == SOLD) {
            System.out.println("Sorry, you already turned the crank");
        } else if (state == SOLD_OUT) {
            System.out.println("You can't eject, you haven't inserted a quarter yet");
        }
    }
 
    // 顾客试着转动曲柄
    public void turnCrank() {
        if (state == SOLD) {
            System.out.println("Turning twice doesn't get you another gumball!");
        } else if (state == NO_QUARTER) {
            System.out.println("You turned but there's no quarter");
        } else if (state == SOLD_OUT) {
            System.out.println("You turned, but there are no gumballs");
        } else if (state == HAS_QUARTER) {
            System.out.println("You turned...");
            state = SOLD;
            dispense();
        }
    }
 
    // 调用此方法,发放糖果
    private void dispense() {
        if (state == SOLD) {
            System.out.println("A gumball comes rolling out the slot");
            count = count - 1;
            if (count == 0) {
                System.out.println("Oops, out of gumballs!");
                state = SOLD_OUT;
            } else {
                state = NO_QUARTER;
            }
        } else if (state == NO_QUARTER) {
            System.out.println("You need to pay first");
        } else if (state == SOLD_OUT) {
            System.out.println("No gumball dispensed");
        } else if (state == HAS_QUARTER) {
            System.out.println("No gumball dispensed");
        }
    }
 
    public void refill(int numGumBalls) {
        this.count = numGumBalls;
        state = NO_QUARTER;
    }

    public String toString() {
        StringBuffer result = new StringBuffer();
        result.append("\nMighty Gumball, Inc.");
        result.append("\nJava-enabled Standing Gumball Model #2004\n");
        result.append("Inventory: " + count + " gumball");
        if (count != 1) {
            result.append("s");
        }
        result.append("\nMachine is ");
        if (state == SOLD_OUT) {
            result.append("sold out");
        } else if (state == NO_QUARTER) {
            result.append("waiting for quarter");
        } else if (state == HAS_QUARTER) {
            result.append("waiting for turn of crank");
        } else if (state == SOLD) {
            result.append("delivering a gumball");
        }
        result.append("\n");
        return result.toString();
    }
}

现在,让我们进入一个小小的内部测试,看下是否符合了要求。

public class WinnerState implements State {
    GumballMachine gumballMachine;
 
    public WinnerState(GumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }
 
    public void insertQuarter() {
        System.out.println("Please wait, we're already giving you a Gumball");
    }
 
    public void ejectQuarter() {
        System.out.println("Please wait, we're already giving you a Gumball");
    }
 
    public void turnCrank() {
        System.out.println("Turning again doesn't get you another gumball!");
    }
 
    public void dispense() {
        gumballMachine.releaseBall();
        if (gumballMachine.getCount() == 0) {
            gumballMachine.setState(gumballMachine.getSoldOutState());
        } else {
            gumballMachine.releaseBall();
            System.out.println("YOU'RE A WINNER! You got two gumballs for your quarter");
            if (gumballMachine.getCount() > 0) {
                gumballMachine.setState(gumballMachine.getNoQuarterState());
            } else {
                System.out.println("Oops, out of gumballs!");
                gumballMachine.setState(gumballMachine.getSoldOutState());
            }
        }
    }
 
    public void refill() { }
    
    public String toString() {
        return "despensing two gumballs for your quarter, because YOU'RE A WINNER!";
    }
}

运行结果比较长,在这里就不进行打印啦,需要的朋友请自行根据代码进行执行。

变更需求来了,需要新设计

现在,客户要求当曲柄转动时,有10%的几率掉下来的是两颗糖果(多送你一颗),那你应该怎么做呢?

我们的计划是这样的:不要维护我们现有的代码,我们重写它以便于将状态对象封装在各自的类中,然后在动作发生时委托给当前状态。所以,我们要做的事情就是:

  1. 首先,我们定义一个State接口。在这个接口中,糖果机的每个动作都有一个对应的方法
  2. 然后为机器中的每个状态实现状态类。这些将负责在对应的状态下进行机器的行为
  3. 最后,我们要摆脱旧的条件代码,取而代之的方式是,将动作委托到状态类

你将会看到,我们不仅遵守了设计原则,实际上我们还实现了状态模式。接下来,我们定义状态接口和类,如下:

好了,到现在为止,我们下一步肯定是要去实现怎么改造了,对吧。在这里呢,给大家先留着,先去思考思考,如何进行改造。思路有了,类图有了,就看你怎么想啦。我们下一次揭晓。

爱生活,爱学习,爱感悟,爱挨踢