《重构与模式》简化(策略模式)-积木系列
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(); } } }
注意到策略模式并不是一个能够单独使用的模式,因为它暴露给客户端具体的策略。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 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)