标签:string 调用 lock color bsp 例子 static 决定 margin
if (vipType == 1) { } if (vipType == 2) { } if (vipType == 1 && null != pricePromotion && null != pricePromotion.getVipPrice()) { } else if (vipType == 2 && null != priceInfo && null != priceInfo.getOldPrice()) { } else if (null != pricePromotion && null != pricePromotion.getAppPrice()) } else { } }
如果我们想到用策略模式,可以把vipType这个条件抽离出来,分裂出2个策略。
这里贴一下例子代码:
场景是,客户端需要不同身份状态下是取得不同策略的优惠信息。
public interface PromotionStrategy { void buildPromotion(); } public class CustomerStrategy implements PromotionStrategy{ public void buildPromotion() { } } public class VipStrategy implements PromotionStrategy{ public void buildPromotion() { } } public class StrategyContext { PromotionStrategy strategy; public void setStrategy(PromotionStrategy strategy) { this.strategy = strategy; } void buildPromotion( ){ strategy.buildPromotion(); } } public class Cilent { public static void main(String[] args) { String status = args[0]; if("customer".equals(status)){ StrategyContext strategyContext = new StrategyContext(); strategyContext.setStrategy(new CustomerStrategy()); strategyContext.buildPromotion(); } else if("vip".equals(status)){ StrategyContext strategyContext = new StrategyContext(); strategyContext.setStrategy(new VipStrategy()); strategyContext.buildPromotion(); } } }
注意到策略模式并不是一个能够单独使用的模式,因为它暴露给客户端具体的策略。
标签:string 调用 lock color bsp 例子 static 决定 margin
原文地址:http://www.cnblogs.com/killbug/p/7095169.html