• 设计模式 策略模式


    策略模式(Strategy)定义了算法家族,分别封装起来,让他们之间可以相互转换,此模式让算法的变化,不会影响到使用算法的客户,即让算法独立于使用它的客户而独立变化。

    策略模式由抽象策略角色(策略类,由一个接口或者抽象类实现)、具体策略角色(具体策略类,包装相关的算法和行为)、环境角色(引用策略类)。

        abstract class Strategy
        {
            //算法方法
            public abstract void AlgorithmInterface();
        }
    抽象策略角色-抽象算法类
        //具体算法A
        class ConcreteStrategyA : Strategy
        {
            //算法A实现方法
            public override void AlgorithmInterface()
            {
                Console.WriteLine("算法A实现");
            }
        }
        //具体算法B
        class ConcreteStrategyB : Strategy
        {
            //算法B实现方法
            public override void AlgorithmInterface()
            {
                Console.WriteLine("算法B实现");
            }
        }
        //具体算法C
        class ConcreteStrategyC : Strategy
        {
            //算法C实现方法
            public override void AlgorithmInterface()
            {
                Console.WriteLine("算法C实现");
            }
        }
    具体策略角色-具体算法类
        //上下文
        class Context
        {
            Strategy strategy;
    
            public Context(Strategy strategy)
            {
                this.strategy = strategy;
            }
            //上下文接口
            public void ContextInterface()
            {
                strategy.AlgorithmInterface();
            }
        }
    环境角色-上下文
            static void Main(string[] args)
            {
                Context context;
    
                context = new Context(new ConcreteStrategyA());
                context.ContextInterface();
    
                context = new Context(new ConcreteStrategyB());
                context.ContextInterface();
    
                context = new Context(new ConcreteStrategyC());
                context.ContextInterface();
    
                Console.Read();
            }
    客户端应用


    策略模式与工厂模式的区别,详见博友随笔http://www.cnblogs.com/me115/p/3790615.html

  • 相关阅读:
    Python之socket
    Python之创建low版的线程池
    Python之面向对象及相关
    Python之面向对象(进阶篇)
    Python之面向对象(初级篇)
    Python之线程与进程
    python中执行父类的构造方法
    python之反射
    记一次有趣的米筐经历~
    算法第四章作业
  • 原文地址:https://www.cnblogs.com/YuanSong/p/4251430.html
Copyright © 2020-2023  润新知