【策略模式】:它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化,不会影响到客户代码;
策略模式是一种定义一系列的算法的方法,从概念上来看,所有这些算法完成的是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。
换句话说,策略模式是用来封装算法的。
【示例代码】:
// 算法抽象基类;
using System;
abstract class Strategy
{
public abstract void AlgorithmInterface();
}
//实际实现算法A
class ConcreteStrategyA : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine("算法A实现");
}
}
//实际实现算法B
class ConcreteStrategyB : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine("算法B实现");
}
}
//实际实现算法C
class ConcreteStrategyC : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine("算法C实现");
}
}
// Context 上下文,用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用;
class Context
{
Strategy strategy;
public Context(Strategy strategy)
{
this.strategy = strategy;
}
//上下文接口;
public void ContextInterface()
{
strategy.AlgorithmInterface();
}
}
class APP
{
static void Main()
{
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();
}
}
实例:商场促销
【实现代码】
using System;
abstract class CashSuper
{
public abstract void AcceptCash();
}
class CashNormal:CashSuper
{
public override void AcceptCash()
{
Console.WriteLine("Sells Normal!");
}
}
class CashRebate:CashSuper
{
public override void AcceptCash()
{
Console.WriteLine("Rebate Selling!");
}
}
class CashReturn:CashSuper
{
public override void AcceptCash()
{
Console.WriteLine("Sells Return!");
}
}
class CashContext
{
private CashSuper cashSuper;
public CashContext(CashSuper cashSuper)
{
this.cashSuper=cashSuper;
}
public void GetResult()
{
cashSuper.AcceptCash();
}
}
class App
{
static void Main()
{
CashContext ch=new CashContext(new CashNormal());
ch.GetResult();
CashContext ch2=new CashContext(new CashRebate());
ch2.GetResult();
CashContext ch3=new CashContext(new CashReturn());
ch3.GetResult();
Console.Read();
}
}