using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StrategyTest
{
class Program
{
static void Main(string[] args)
{
Context context = new Context(new StrategyA());
context.operate();
context = new Context(new StrategyB());
context.operate();
context = new Context(new StrategyC());
context.operate();
Console.Read();
}
}
interface IStrategy
{
void operate();
}
class StrategyA : IStrategy
{
public void operate()
{
Console.WriteLine("执行策略A");
}
}
class StrategyB : IStrategy
{
public void operate()
{
Console.WriteLine("执行策略B");
}
}
class StrategyC : IStrategy
{
public void operate()
{
Console.WriteLine("执行策略C");
}
}
class Context
{
private IStrategy strategy;
public Context(IStrategy strategy)
{
this.strategy = strategy;
}
public void operate()
{
strategy.operate();
}
}
}
运行效果