策略模式定义了一系列的算法,并将每一个算法封装起来,使它们可以相互替换。策略模式让算法的变化独立于使用算法的客户。
// 策略接口
public interface IStrategy
{
void Execute();
}
// 具体策略A
public class ConcreteStrategyA : IStrategy
{
public void Execute()
{
Console.WriteLine("Executing strategy A");
}
}
// 具体策略B
public class ConcreteStrategyB : IStrategy
{
public void Execute()
{
Console.WriteLine("Executing strategy B");
}
}
// 上下文类,接收客户的请求并使用某种策略
public class Context
{
private IStrategy _strategy;
public Context(IStrategy strategy)
{
_strategy = strategy;
}
public void SetStrategy(IStrategy strategy)
{
_strategy = strategy;
}
public void ExecuteStrategy()
{
_strategy.Execute();
}
}
// 客户端代码
class Program
{
static void Main(string[] args)
{
Context context = new Context(new ConcreteStrategyA());
context.ExecuteStrategy();
context.SetStrategy(new ConcreteStrategyB());
context.ExecuteStrategy();
}
}