namespace ConsoleApplication4
{
using System;
class Program
{
static void Main(string[] args)
{
Context context;
//实例化不同的策略
context = new Context(new ConcreteStrategyA());
context.ContextInterface();
context = new Context(new ConcreteStrategyB());
context.ContextInterface();
context = new Context(new ConcreteStrategyC());
context.ContextInterface();
Console.Read();
}
}
//抽象算法类
abstract class Strategy
{
//算法方法
public abstract void Algorithmlnterface();
}
//具体算法A
class ConcreteStrategyA : Strategy
{
//算法A实现方法
public override void Algorithmlnterface()
{
Console.WriteLine("算法A实现");
//throw new NotImplementedException();
}
}
//具体算法B
class ConcreteStrategyB : Strategy
{
//算法B实现方法
public override void Algorithmlnterface()
{
Console.WriteLine("算法B实现");
//throw new NotImplementedException();
}
}
//具体算法C
class ConcreteStrategyC : Strategy
{
//算法C实现方法
public override void Algorithmlnterface()
{
Console.WriteLine("算法C实现");
//throw new NotImplementedException();
}
}
//上下文
class Context
{
Strategy strategy;
//构造函数,初始化时,传入具体的策略对象
public Context(Strategy strategy)
{
this.strategy = strategy;
}
//上下文接口,根据具体的策略对象,调用其算法的方法
public void ContextInterface()
{
strategy.Algorithmlnterface();
}
}
}