设计模式之策略模式(Strategy)
2010-01-15 22:22 key_sky 阅读(238) 评论(0) 编辑 收藏 举报 面向对象的编程,并不是类越多越好,类的划分是为了封装,分类的基础是抽象,具有相同属性和功能的对象的抽象集合才是类.
策略模式(Strategy):定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户。从概念上看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合.
优点:Strategy类层次为Context定义一系列可供重用的方法和行为。继承有助于析取这些算法中的公共功能。简化单元测试,每个算法都有自己的类,可以通过自己的接口单独测试.
缺点:选择所用具体实现的职责由客户端对象承担,并转给策划模式的Context对象,本身没有解除客户端选择判断压力,可以用简单工厂模式结合,减轻客户端职责。
Strategy.cs:
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
using System;
using System.Collections.Generic;
using System.Text;
//面向对象的编程,并不是类越多越好,类的划分是为了封装,分类的基础是抽象,具有相同属性和
//功能的对象的抽象集合才是类
//策略模式(Strategy):定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的
//变化,不会影响到使用算法的客户。从概念上看,所有这些算法完成的都是相同的工作,只是现实
//不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合
//优点:Strategy类层次为Context定义一系列可供重用的方法和行为。继承有助于析取这些算法中的
//公共功能。简化单元测试,每个算法都有自己的类,可以通过自己的接口单独测试
//缺点:选择所用具体实现的职责由客户端对象承担,并转给策划模式的Context对象,本身没有解除
//客户端选择判断压力,可以用简单工厂模式结合,减轻客户端职责
namespace ConsoleApplication1
{
class Strategy2
{
}
//抽象算法类
abstract class Strategy
{
//算法方法
public abstract void AlgorithmInterface();
}
//具体算法
class ConcreteStrategyA : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine("算法A实现");
}
}
class ConcreteStrategyB : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine("算法B实现");
}
}
class ConcreteStrategyC : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine("算法C实现");
}
}
//维护对Strategy对象的引用
class Context
{
Strategy strtegy;
public Context(Strategy strategy2)
{
this.strtegy = strategy2;
}
public void ContextInterface()
{
strtegy.AlgorithmInterface();
}
}
}
Program.cs:
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
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();
}
}
}
运行结果:
算法A实现
算法B实现
算法C实现