设计模式之状态模式(state model)
状态模式适用于实际类型之间需要不断切换,如商品、结账、实际支付这样一条龙流水线,这期间存在着一个session用户的状态切换。通过一个实现了接口的控制器类来控制各实际类状态的切换,具体控制实现的方法是在另一个上下文类中实现。各实现类都实现了单例模式。
package StateMethod;
public interface IShopState {
public void shop();
public void generateBill();
public void pay();
//protected void changeState(ShopContext c, IShopState);
}
package StateMethod;
public class ShopState implements IShopState {
public ShopState() {
}
public void shop() { }
public void generateBill() { }
public void pay() { }
protected void changeState(ShopContext c, ShopState s) {
c.changeState(s);
}
}
package StateMethod;
public class Shop extends ShopState {
public static boolean instanceFlag = false; //true if have 1 instance
private Shop() {
}
public static Shop getInstance() {
if(! instanceFlag) {
instanceFlag = true;
return new Shop();
}
return null;
}
public void shop() {
System.out.println("The state is shopping now !");
}
}
package StateMethod;
public class GenerateBill extends ShopState {
public static boolean instanceFlag = false; //true if have 1 instance
private GenerateBill() {
}
public static GenerateBill getInstance() {
if(! instanceFlag) {
instanceFlag = true;
return new GenerateBill();
}
return null;
}
public void generateBill() {
System.out.println("The state is generating bill now !");
}
}
package StateMethod;
public class Pay extends ShopState {
public static boolean instanceFlag = false; //true if have 1 instance
private Pay() {
}
public static Pay getInstance() {
if(! instanceFlag) {
instanceFlag = true;
return new Pay();
}
return null;
}
public void pay() {
System.out.println("The state is pay now !");
}
}
package StateMethod;
public class ShopContext {
private ShopState currentState;
public ShopContext() {
}
public void changeState(ShopState s) {
currentState = s;
}
public void shop() {
currentState.shop();
}
public void generateBill() {
currentState.generateBill();
}
public void pay() {
currentState.pay();
}
}
package StateMethod;
public class Test {
public static void main(String[] args) {
ShopContext myContext = new ShopContext();
ShopState myShop = Shop.getInstance();
ShopState myGenBill = GenerateBill.getInstance();
ShopState myPay = Pay.getInstance();
myContext.changeState(myShop);
myContext.shop();
myContext.changeState(myGenBill);
myContext.generateBill();
myContext.changeState(myPay);
myContext.pay();
myShop.changeState(myContext, myPay);
myContext.pay();
}
}
输出:
The state is shopping now !
The state is generating bill now !
The state is pay now !
The state is pay now !