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

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   每当变幻时  阅读(409)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
历史上的今天:
2012-06-29 awk入门(一直在改变系列1)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示