说说设计模式~策略模式(Strategy)

返回目录

策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。而对于客户端(UI)来说,可以通过IOC再配合工厂模块,实现动态策略的切换,策略模块通常于一个抽象策略对象(interface or abstract class),多个具体策略对象(implement class )和一个调用策略的入口组成。

何时能用到它?

对于UI来说,可能一个功能会有多种实现方式,而且实现方式可能还会有扩展,例如,一个ATM机,它目前支持工行,建行,家行,以后可能又出现了占占银行,而这时,ATM机的客户端程序需要扩展一个占占银行的实现策略,这时,使用策略模式就可以实现了,它不需要修改之前的代码,只要扩展一个占占银行实现类即可。

策略模式的结构图

策略模式实现说明

IStrategy:抽象策略对象

ConcreteStrategyA:具体策略A

ConcreteStrategyB:具体策略B

ConcreteStrategyC:具体策略C

Context:客户端调用的入口

策略模式的C#实现

复制代码
#region 策略模式

    // The classes that implement a concrete strategy should implement this
    // The context class uses this to call the concrete strategy
    interface IStrategy
    {
        void Execute();
    }

    // Implements the algorithm using the strategy interface
    class ConcreteStrategyA : IStrategy
    {
        public void Execute()
        {
            Console.WriteLine("Called ConcreteStrategyA.Execute()");
        }
    }

    class ConcreteStrategyB : IStrategy
    {
        public void Execute()
        {
            Console.WriteLine("Called ConcreteStrategyB.Execute()");
        }
    }

    class ConcreteStrategyC : IStrategy
    {
        public void Execute()
        {
            Console.WriteLine("Called ConcreteStrategyC.Execute()");
        }
    }

    // Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
    class Context
    {
        IStrategy strategy;

        // Constructor
        public Context(IStrategy strategy)
        {
            this.strategy = strategy;
        }

        public void Execute()
        {
            strategy.Execute();
        }
    }

    #endregion
复制代码

 

返回目录

posted @   张占岭  阅读(1501)  评论(0编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
历史上的今天:
2012-08-07 树型结构~无限级联下拉列表框
点击右上角即可分享
微信分享提示