• 设计模式学习总结(八)策略模式(Strategy)


      策略模式,主要是针对不同的情况采用不同的处理方式。如商场的打折季,不同种类的商品的打折幅度不一,所以针对不同的商品我们就要采用不同的计算方式即策略来进行处理。

      一、示例展示:

      以下例子主要通过对手机和笔记本添加不同的策略来实现策略模式的应用!

      1. 创建抽象策略角色:DailyProductStrategy

    abstract class DailyProductStrategy
    {
        public abstract void AlgorithmInterface();
    }
    View Code

      2. 创建具体策略角色:Handphone

    class Handphone : DailyProductStrategy
    {
        public override void AlgorithmInterface()
        {
            Console.WriteLine("Strategy A is using for handphone!");
        }
    }
    View Code

      3. 创建具体策略角色:Laptop

    class Laptop : DailyProductStrategy
    {
        public override void AlgorithmInterface()
        {
            Console.WriteLine("Strategy B is using for laptop!");
        }
    }
    View Code

      4. 创建环境角色:Context

    class Context
    {
        DailyProductStrategy strategy;
    
        public Context(DailyProductStrategy strategy)
        {
            this.strategy = strategy;
        }
    
        public void ContextInterface()
        {
            strategy.AlgorithmInterface();
        }
    }
    View Code

      5. 创建客户端调用:

    class Program
    {
        static void Main(string[] args)
        {
            Context c = new Context(new Handphone());
            c.ContextInterface();
    
            Context d = new Context(new Laptop());
            d.ContextInterface();
    
            Console.ReadLine();
        }
    }
    View Code

      二、策略模式设计理念:

      策略模式主要包括三个角色:抽象策略角色,具体策略角色及环境角色。通过对策略中的不确定部分进行抽象,然后在具体策略角色中通过继承来实现不同的策略的实现细节。在环境角色中定义抽象策略对象,通过环境角色的构造方法,实现了对该抽象策略对象的初始化,也为策略模式的实现提供了最根本的灵活性!

      三、角色及关系:

       

  • 相关阅读:
    git查看远程仓库地址命令
    sublime 安装插件GitGutter报错,git binary cannot be found等等
    sublime 中 pyv8 binary 报错怎么处理?
    经典语录(个人喜欢)
    css水平垂直居中对齐方式
    github怎么退出组织和删除自己创建的组织
    js学习篇1--数组
    js学习篇--数组按升序降序排列
    tp5.1 swoole 实现异步处理
    验证sll证书与密钥
  • 原文地址:https://www.cnblogs.com/sccd/p/6592448.html
Copyright © 2020-2023  润新知