策略模式,定义一系列算法类,将每一个算法封装起来,并让他们可以相互替换。策略模式是把算法独立出来,让用户选择使用
interface IStrategy
{
void Algorithm();
}
class ConcreteStrategyA:IStrategy
{
public void Algorithm()
{
Console.WriteLine("使用A算法");
}
}
class ConcreteStrategyB : IStrategy
{
public void Algorithm()
{
Console.WriteLine("使用B算法");
}
}
//环境上下文
class Context
{
private IStrategy strategy;
public Context(IStrategy strategy)
{
this.strategy = strategy;
}
public void Algorithm()
{
strategy.Algorithm();
}
}
class Program
{
static void Main()
{
IStrategy strategy = new ConcreteStrategyA();
Context context = new Context(strategy);
context.Algorithm();
Console.Read();
}
}