设计模式学习总结9 行为型4 Strategy策略模式

Strategy策略模式(行为型)

作用
策略模式将类中的算法分离出放在一个单独的类中。不同的算法适用于不同的问题。如果所有的算法都集中在一个类中定会导致带有条件选择的杂乱的代码。策略模式使得客户端能够轻松的从一系列算法中找出适合自己的算法。这些算法可以不依赖他们用到的数据来表示。

Role
The Strategy pattern involves removing an algorithm from its host class and putting it in a separate class. There may be different algorithms (strategies) that are applicable for a given problem. If the algorithms are all kept in the host, messy code with lots of conditional statements will result. The Strategy pattern enables a client to choose which algorithm to use from a family of algorithms and gives it a simple way to access it. The
algorithms can also be expressed independently of the data they are using.

设计


Context,维护策略对象使用算法的上下文信息
IStrategy,所有策略的公共接口
StrategyA, StrategyB,实现了策略接口的具体策略

举例

Context,印刷图书
Strategy,使用某种技术的印刷设备
Algorithem,具体的印刷技术,如喷墨,胶印
IStrategy,印刷

实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Strategy
{
       
// The Context
       class Context 
       {
          
// Context state
          public const int start = 5;
          
public int Counter = 5;

          
// Strategy aggregation
          IStrategy strategy = new Strategy1();

          
// Algorithm invokes a strategy method
          public int Algorithm() 
          {
            
return strategy.Move(this);
          }

          
// Changing strategies
          public void SwitchStrategy() 
          {
            
if (strategy is Strategy1)
                strategy 
= new Strategy2();
            
else
                strategy 
= new Strategy1();
          }
       }

        
// Strategy interface
        interface IStrategy 
        {
          
int Move (Context c);
        }
        
// Strategy 1
        class Strategy1 : IStrategy 
        {
          
public int Move (Context c) 
          {
            
return ++c.Counter;
          }
        }

        
// Strategy 2
        class Strategy2 : IStrategy 
        {
          
public int Move (Context c) 
          {
            
return --c.Counter ;
          }
        }

    
class Program
    {
        
static void Main(string[] args)
        {
            Context context 
= new Context();
            context.SwitchStrategy();
            Random r 
= new Random(37);
            
for (int i=Context.start; i<=Context.start+15; i++
            {
              
if (r.Next(3== 2
              {
                Console.Write(
"|| ");
                context.SwitchStrategy();
              }
              Console.Write(context.Algorithm() 
+"  ");
            }
            Console.WriteLine();
            Console.ReadLine();
        }
    }
}

输出:

 /* Output
      4  || 5  6  7  || 6  || 7  8  9  10  || 9  8  7  6  || 7  || 6  5
 */

应用场景
1、需要很多仅仅是行为不同的类
2、一个目的但是会有不同的算法来实现,选择算法的标准是可以编程实现的
3、客户端不能访问算法使用的数据

Use the Strategy pattern when…
•  Many related classes differ only in their behavior.
•  There are different algorithms for a given purpose, and the selection criteria can be codified.
•  The algorithm uses data to which the client should not have access.

总结

Strategy策略模式是一种行为型模式。主要解决对象使用的算法可能会多种多样,经常发生变化。如果在对象内部实现这些算法,将会使对象的代码变得异常复杂,甚至会造成性能上的负担。GoF《设计模式》中说道:定义一系列算法,把它们一个个封装起来,并且使它们可以相互替换。该模式使得算法可独立于它们的客户变化。
Strategy模式的要点:

1Strategy及其子类为组件提供了一系列可重用的算法,从而可以使得类型在运行时方便地根据需要在各个算法之间进行切换。所谓封装算法,支持算法的变化。
2Strategy模式提供了用条件判断语句以外的另一中选择,消除条件判断语句,就是在解耦合。含有许多条件判断语句的代码通常都需要Strategy模式。
3Strategy模式以算法为中心,可以和Factory Method联合使用,在工厂中使用配制文件对变化的点进行动态的配置。这样就使变化放到了运行时。
4Strategy模式集中在算法的封装上

原文地址:https://www.cnblogs.com/utopia/p/1679997.html