zoukankan      html  css  js  c++  java
  • Strategy Pattern策略模式

    http://www.cnblogs.com/zhili/p/StragetyPattern.html

    http://www.dofactory.com/net/strategy-design-pattern

    主要是对方法的封装。

    Definition

    Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
    定义了一组算法,封装每一个,让它们变得可替代的。策略使得算法独立于使用它的客户端。
     

    Participants

        The classes and objects participating in this pattern are:   

       在策略模式中的类以及对象

    • Strategy  (SortStrategy)  策略
      • declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy

                   声明一个接口,此接口针对于所有支持的算法。上下文使用这个接口调用算法(由具体的策略定义的具体算法)

    • ConcreteStrategy  (QuickSort, ShellSort, MergeSort)   具体的策略
      • implements the algorithm using the Strategy interface

                 使用策略接口实现算法

    • Context  (SortedList)    上下文
      • is configured with a ConcreteStrategy object    由具体策略对象配置
      • maintains a reference to a Strategy object        维持一个策略对象的引用
      • may define an interface that lets Strategy access its data.    定义一个接口对象,允许策略访问数据

    Structural code in C#

    This structural code demonstrates the Strategy pattern which encapsulates functionality in the form of an object. This allows clients to dynamically change algorithmic strategies.

    结构化的代码展示了策略模式,以对象的形式封装功能。这种方式,允许客户端动态地改变算法策略。

    abstract class Strategy
        {
            internal abstract void Sort();
        }
     class ConcreteStrategyA : Strategy
        {
            internal override void Sort()
            {
                Console.WriteLine("排序算法A");
            }
        } 
    class ConcreteStrategyB : Strategy
        {
            internal override void Sort()
            {
                Console.WriteLine("排序算法B");    
            }
        }
    
    class Context
        {
            private Strategy strategy;
    
            internal Context(Strategy s)
            {
                strategy = s;
            }
    
            internal void Sort()
            {
                strategy.Sort();
            }
        }
    class Program
        {
            static void Main(string[] args)
            {
                Context context;
    
                context = new Context(new ConcreteStrategyA());
                context.Sort();
    
                context = new Context(new ConcreteStrategyB());
                context.Sort();
    
                Console.ReadKey();
            }
        }
  • 相关阅读:
    JoymobilerV2.2.1发布
    对fckstyles.xml加载失败问题的解决
    角摩网改版了,突出手机电子书,手机游戏,手机软件等栏目
    J2ME的学习--编译出错
    角摩手机电子书生成专家 V2.1发布,可以合并txt,umd小说
    jmbook.dat的手机电子书格式
    Joymobiler角摩手机电子书生成专家
    绿色小巧的手机电子书制作+阅读器(支持txt,jar,umd,chm)V2.3发布
    角摩网给各网站提供在线手机电子书制作接口
    joymbiler角摩电子书专家升级至V2.6
  • 原文地址:https://www.cnblogs.com/chucklu/p/4495526.html
Copyright © 2011-2022 走看看