策略模式:定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
- 策略模式是一种定义了一系列算法的方法,所有这些算法完成的都是相同的工作,只是实现不同,他可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。
- 策略模式有两个类:
一、Context类:用一个具体的策略来配置,并维护一个对具体策略的对象的引用。
二、Strategy类:该类拥有一个算法的公共接口。具体策略的实现从这个类派生。
- 策略模式的Strategy类层次为Context定义了一系列的可供重用的算法或行为。
- 策略模式就是用来封装算法的,只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。
例子如下:
Strategy类:
abstract class Strategy
{
public abstract void AlgorithmInterface();
}
StrategyA类:具体策略实现
class StrategyA:Strategy
{
public override void AlgorithmInterface()
{
//A具体实现。
}
}
StrategyB类:具体策略实现
class StrategyB:Strategy
{
public override void AlgorithmInterface()
{
//B具体实现。
}
}
class Context
{
Strategy strategy;
public Context(Strategy strategy)
{
this.strategy=strategy;
}
//上下文接口。
public void ContextInterface()
{
strategy.AlgorithmInterface();
}
}