策略模式
策略模式:定义一系列算法的方法,才概念上看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有算法,减少了各种算法类与使用算法类之间的耦合。
策略模式就是用来封装算法的,但在实践中,我们发现可以用它来封装任何类型的规则,只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。
策略模式的Strategy类层次为Context定义了一系列
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 32 | abstract class Strategy{ public abstract void AlgorithmInterface(); } class StrategyA extend Strategy{ public AlgorithmInterface(){ //A实现 }; } class StrategyB extend Strategy{ public AlgorithmInterface(){ //B实现 }; } class StrategyC extend Strategy{ public AlgorithmInterface(){ //C实现 }; } class Context(){ Strategy strategy; public Context(bufferType:Srting){ //可以搭配简单工厂模式一起使用 var strategy = null ; switch (bufferType){ case "a" :strategy = new StrategyA(); case "b" :strategy = new StrategyB(); case "c" :strategy = new StrategyC(); } this .strategy = buffer; } public ContextInterface(){ this .strategy.AlgorithmInterface(); } } class Main{ Context context = new Context( "a" ); context.ContextInterface(); } |
//在客户端使用只需要根据客户需要实例化不同的Strategy类型传入Context中,然后调用算法即可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?