1、定义:
策略模式定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的好处。
2、问题:一类事物,有很多子类,如果管理这些子类,何时调用哪个子类。
3、解决方案:
策略模式和简单工厂类似,用简单工厂解决的问题,也可以用策略模式解决,实现方式有所不同。
1)、抽象父类,抽象父类中创建需要的属性和抽象虚操作方法。
2)、子类,子类继承自上面创建的抽象父类,重写父类里的虚函数。
3)、操作上下文类,传入上面对应的子类,调用子类的方法,就是一个管理类。
4、UML类图:

5、示例代码:
1)、抽象父类:
public abstract class Strategy
{
public abstract void AligorithmInterface();
}
2)、子类:
public class StrategyA:Strategy
{
public override void AligorithmInterface()
{
......
}
}
public class StrategyB:Strategy
{
public override void AligorithmInterface()
{
......
}
}
3)、上下文管理类:
public class Context
{
Strategy _Strategy;
public Context(Strategy strategy)
{
this._Strategy=strategy;
}
public void ContextInterface()
{
this._Strategy.AligorithmInterface();
}
}
4)、客户端调用:
Context context=new Context(new StrategyA());
context.ContextInterface();
Context context=new Context(new StrategyB());
context.ContextInterface();
说明:这个模式也可以和简单工厂混合使用:
public class Context
{
Strategy _Strategy;
public Context(string type)
{
switch (type)
{
case "A":
_Strategy=new StrategyA();
break;
case "B":
_Strategy=new StrategyB();
break;
}
}
public void ContextInterface()
{
this._Strategy.AligorithmInterface();
}
}
浙公网安备 33010602011771号