状态模式–自动售货机
咖啡自动售货机共有3种状态,分别是“有咖啡,无人投币”、“有咖啡,有人投币”和“无咖啡”。咖啡自动售货机有两个方法:needAnCoin( )和sellCoffee( )。
咖啡自动售货机的默认初始状态是“有咖啡,无人投币”。当咖啡自动售货机处于“有咖啡,无人投币”状态时,调用sellCoffee( )方法将显示“需投一元硬币,才可以得到一杯咖啡”,并保持当前的状态;调用needAnCoin( )方法将显示“咖啡机里被投入了一元硬币”,然后咖啡自动售货机将处于“有咖啡,有人投币”状态,此时,如果调用sellCoffee( )方法将显示“送出一杯咖啡”,然后咖啡自动售货机将处于“有咖啡,无人投币”状态或“无咖啡”状态;当咖啡白动售货机处于“无咖啡”状态时,调用giveAnCupCoffee( )方法将显示“没有咖啡了,请拨111111服务电话”,调用needAnCoin( )方法将显示“投币无效,退回!”
结构如下:
1.工程文件
2.State.java
package state_mode;
public abstract class State{
int coffeeCount; //记录一共有多少杯咖啡
public abstract void giveAnCupCoffee();
public abstract void comeInCoin();
}
3.HaveNotCoffee.java
package state_mode;
public class HaveNotCoffee extends State{
AutoCoffeeMachine machine;
HaveNotCoffee(AutoCoffeeMachine machine){
this.machine=machine;
}
public void giveAnCupCoffee( ){
System.out.println("没咖啡了,请拨111111");
}
public void comeInCoin( ){
System.out.println("投币无效,退回!");
}
}
4.HaveCoffeeNoCoin.java
package state_mode;
public class HaveCoffeeNoCoin extends State{
AutoCoffeeMachine machine;
HaveCoffeeNoCoin(AutoCoffeeMachine machine){
this.machine=machine;
}
public void giveAnCupCoffee(){
System.out.println("需投入一元,才可得一杯");
}
public void comeInCoin(){
System.out.println("投入了一元硬币");
machine.setState(machine.haveCoffeeAndCoin); }
}
5.HaveCoffeeAndCoin.java
package state_mode;
public class HaveCoffeeAndCoin extends State{
AutoCoffeeMachine machine;
HaveCoffeeAndCoin(AutoCoffeeMachine machine){
this.machine=machine; }
public void giveAnCupCoffee( ){
int n=machine.haveCoffeeNoCoin.coffeeCount;
if(n>1) { n--;
System.out.println("送出一杯咖啡");
machine.haveCoffeeNoCoin.coffeeCount = n;
machine.setState(machine.haveCoffeeNoCoin);
} else if(n==1) { n--;
System.out.println("送出一杯咖啡");
machine.setState(machine.haveNotCoffee); }
}
public void comeInCoin( ){
System.out.println("目前不允许投币");
} }
6.AutoCoffeeMachine.java
package state_mode;
public class AutoCoffeeMachine {
State haveCoffeeNoCoin,haveCoffeeAndCoin,haveNotCoffee;
State state;
AutoCoffeeMachine( ){
haveCoffeeNoCoin=new HaveCoffeeNoCoin(this);
haveCoffeeAndCoin=new HaveCoffeeAndCoin(this);
haveNotCoffee=new HaveNotCoffee(this);
haveCoffeeNoCoin.coffeeCount=3;
state=haveCoffeeNoCoin; //设置售货机初始状态
}
public void sellCoffee( ){ state.giveAnCupCoffee( ); }
public void needAnCoin( ){ state.comeInCoin( ); }
public void setState(State state){ this.state=state; }
}
7.Application.java
package state_mode;
public class Application{
public static void main(String args[ ]){
AutoCoffeeMachine machine = new AutoCoffeeMachine( );
machine.sellCoffee( ); machine.needAnCoin( );
machine.sellCoffee( ); machine.needAnCoin( );
machine.sellCoffee( ); machine.needAnCoin( );
machine.sellCoffee( ); machine.needAnCoin( );
machine.sellCoffee( );
}
}