设计模式学习之策略模式

来源:互联网 发布:mac的插件在哪里管理 编辑:程序博客网 时间:2024/05/19 19:15

策略模式:它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的改变,不会影响到使用算法的客户。[摘录]

单独的策略模式:

先上一张UML类图


说明一下:

策略类Strategy,定义了所有支持的算法的公共接口,可以是一个抽象类。

ConcreteStrategyA或者B、C封装了具体的算法或者行为,继承Strategy类。override类Strategy中方法。

Context用来维护一个Strategy对象的引用。

再上代码实现:

Strategy.cs

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{    public abstract class Strategy    {        public abstract void AlgorithmInterface();    }}
ConcreteStrategyA.cs

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{    public class ConcreteStrategyA:Strategy    {        public override void AlgorithmInterface()        {            //throw new NotImplementedException();            Console.WriteLine("我实现了策略A的算法。");        }    }}
Context.cs

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{    public class Context    {        Strategy strategy = null;        //初始化时传入具体的策略对象        public Context(Strategy stra)        {            this.strategy = stra;        }        //根据具体的策略对象调用其具体的实现算法        public void ContextInterface()        {            this.strategy.AlgorithmInterface();        }    }}
调用:

            #region 策略模式            Context context = null;            context = new Context(new ConcreteStrategyA());            context.ContextInterface();            Console.ReadLine();            #endregion

但是,这里我们又开始了在调用的时候判断使用哪一个算法了。这个不好。试试简单工厂模式吧,让它与Context结合一下。

这里我更改了Context.cs的代码,增加了以下的那一段:

public Context(string stra)        {            switch (stra)            {                case "a": this.strategy = new ConcreteStrategyA();                    break;                default: break;            }        }
调用的时候:

            #region 策略模式            Context context = null;           // context = new Context(new ConcreteStrategyA());            context = new Context("a");            context.ContextInterface();            Console.ReadLine();            #endregion

再回头看看策略模式,策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合[摘录]。策略Strategy为Context定义了一系列可重用的算法和行为,继承有助于析取出这些算法中的公共功能。策略模式简化了单元测试,每一个方法的实现都有一个单独的类,可以单独进行测试。策略模式封装了变化的东西。它不仅可以封装算法,也可以封装各种业务规则(在业务分析过程中,需要在某些情况下应用不同的业务规则时)。





0 0
原创粉丝点击