一、策略模式(Strategy)
它定义了一系列的算法,将算法都分别封装起来,并且让它们之间可以相互替换(具有共性,有同一个策略接口),独立于使用它的人来独立变化
二、策略模式UML图
三、代码实现
Strategy类,定义所有支持的算法的公共接口
abstract class Strategy
{
//算法方法
public abstract void AlgorithmInterface();
}
ConcereteStrategy(具体策略),封装了具体的算法或行为,继承于Strategy
//具体算法A
class ConcreteStrategyA : Strategy
{
//算法A实现方法
public override void AlgorithmInterface()
{
Console.WriteLine("算法A实现");
}
}
//具体算法B
class ConcreteStrategyB : Strategy
{
//算法B实现方法
public override void AlgorithmInterface()
{
Console.WriteLine("算法B实现");
}
}
//具体算法C
class ConcreteStrategyC : Strategy
{
//算法C实现方法
public override void AlgorithmInterface()
{
Console.WriteLine("算法C实现");
}
}
Context,用一个ConcreteStrategy来配置,维护一个队Strategy对象的引用
class Context
{
Straregy strategy;
public Context(Strategy strategy) //初始化时,传入具体的策略对象
{
this.strategy = strategy;
}
//上下文接口
public void ContextInterface() //根据具体的策略对象,调用其算法的方法
{
strategy.AlgorithmInterface();
}
}
客户端代码
static void Main(string[] args)
{
Context context;
//由于实例化不同的策略,所以最终在调用context.ContextInterface();时,所获得的结果就不完全相同
context = new Context(new ConcerteStrategyA());
context.ContextInterface();
context = new Context(new ConcerteStrategyB());
context.ContextInterface();
context = new Context(new ConcerteStrategyC());
context.ContextInterface();
Console.Read();
}