zoukankan      html  css  js  c++  java
  • 设计模式 策略模式

    策略模式(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

  • 相关阅读:
    [题解] P2513 [HAOI2009]逆序对数列
    [题解]洛谷P2709 小B的询问
    题解 P1944 最长括号匹配_NOI导刊2009提高(1)
    [题解]SP703 SERVICE
    Bzoj2427: [HAOI2010]软件安装
    【题解】UVA11362 Phone List
    【题解】P2922 [USACO08DEC]秘密消息Secret Message
    Tire树的学习
    【题解】P1171 售货员的难题
    计算机与编程资源教程汇总
  • 原文地址:https://www.cnblogs.com/YuanSong/p/4251430.html
Copyright © 2011-2022 走看看