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

    名称 Strategy
    结构  
    意图 定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。
    适用性
    • 许多相关的类仅仅是行为有异。“策略”提供了一种用多个行为中的一个行为来配置一个类的方法。
    • 需要使用一个算法的不同变体。例如,你可能会定义一些反映不同的空间/时间权衡的算法。当这些变体实现为一个算法的类层次时[ H O 8 7 ] ,可以使用策略模式。
    • 算法使用客户不应该知道的数据。可使用策略模式以避免暴露复杂的、与算法相关的数据结构。
    • 一个类定义了多种行为, 并且这些行为在这个类的操作中以多个条件语句的形式出现。将相关的条件分支移入它们各自的S t r a t e g y 类中以代替这些条件语句。
    Code Example
     1// Strategy
     2
     3// Intent: "Define a family of algorithms, encapsultate each one, and make 
     4// them interchangeable. Strategy lets the algorithm vary independently 
     5// from clients that use it." 
     6
     7// For further information, read "Design Patterns", p315, Gamma et al.,
     8// Addison-Wesley, ISBN:0-201-63361-2
     9
    10/* Notes:
    11 * Ideal for creating exchangeable algorithms. 
    12 */

    13 
    14namespace Strategy_DesignPattern
    15{
    16    using System;
    17
    18    
    19    abstract class Strategy 
    20    {
    21        abstract public void DoAlgorithm();
    22    }

    23
    24    class FirstStrategy : Strategy 
    25    {
    26        override public void DoAlgorithm()
    27        {
    28            Console.WriteLine("In first strategy");            
    29        }

    30    }

    31
    32    class SecondStrategy : Strategy 
    33    {
    34        override public void DoAlgorithm()
    35        {
    36            Console.WriteLine("In second strategy");            
    37        }

    38    }

    39
    40    class Context 
    41    {
    42        Strategy s;
    43        public Context(Strategy strat)
    44        {
    45            s = strat;            
    46        }

    47
    48        public void DoWork()
    49        {
    50            // some of the context's own code goes here
    51        }

    52
    53        public void DoStrategyWork()
    54        {
    55            // now we can hand off to the strategy to do some 
    56            // more work
    57            s.DoAlgorithm();
    58        }

    59    }

    60
    61    /// <summary>
    62    ///    Summary description for Client.
    63    /// </summary>

    64    public class Client
    65    {
    66        public static int Main(string[] args)
    67        {    
    68            FirstStrategy firstStrategy = new FirstStrategy();
    69            Context c = new Context(firstStrategy);
    70            c.DoWork();
    71            c.DoStrategyWork();
    72
    73            return 0;
    74        }

    75    }

    76}

    77
    78
  • 相关阅读:
    洛谷P5245 【模板】多项式快速幂
    洛谷P5205 【模板】多项式开根(FFT)
    laravel 数据库连接Mysql
    laravel V层引入css 和js方法
    laravel V层
    小程序地区时间自定义选择器 picker
    点击a标签 跳到当前页面指定div
    图片上下居中
    小程序消除图片下边距的三个方法
    百度地图定位
  • 原文地址:https://www.cnblogs.com/DarkAngel/p/217265.html
Copyright © 2011-2022 走看看