《重构与模式》简化(策略模式)-积木系列

composed method:
我们平时在写代码的过程中也会吧一些复杂的代码分解成几个小方法,以使代码开起来清晰,而composed method只是将实践定义成理论而已。不过我认为他核心的原则是尽可能将重构的方法保持在同一细节水平上。
 
 
strategy:
核心是将复杂条件从算法中抽离,使算法纯净到可以抽象为统一行为的逻辑。如此即可抽象出各种strategy出来。
然后用context来调用各个strategy,而实用哪一个strategy由客户端来决定。
举个例子我们在代码里经常会遇这种代码:
 
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();
        }
    }
}

 

 注意到策略模式并不是一个能够单独使用的模式,因为它暴露给客户端具体的策略。

 

 

 

 

 

posted on 2017-06-29 21:16  每当变幻时  阅读(405)  评论(0编辑  收藏  举报

导航