一、定义
策略模式定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。二、设计原则
1、找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起。
2、针对接口编程,而不是针对实现编程。3、多用组合,少用继承。三、示例
/// <summary>
/// 鸭子类 /// </summary> public abstract class Duck { protected IFlyBehavior flyBehavior; protected IQuackBehavior quackBehavior; public Duck() { }public abstract void Display();
public void PerformFly() { flyBehavior.Fly(); }public void PerformQuack()
{ quackBehavior.Quck(); }public void setFlyBehavior(IFlyBehavior fb)
{ flyBehavior = fb; }public void setQuckBehavior(IQuackBehavior qb)
{ quackBehavior = qb; }public void Swim()
{ Console.WriteLine("鸭子全都会游泳!"); } }/// <summary>
/// 飞行行为 /// </summary> public interface IFlyBehavior { void Fly(); }public class FlyNoWay:IFlyBehavior
{ public void Fly() { Console.WriteLine("不会飞!"); } }public class FlyWithWings :IFlyBehavior
{ public void Fly() { Console.WriteLine("飞飞飞!"); } }public class FlyRocketPower:IFlyBehavior
{ public void Fly() { Console.WriteLine("火箭加速飞!"); } } /// <summary> /// 绿头鸭 /// </summary> public class MallardDuck:Duck { public MallardDuck() { flyBehavior = new FlyWithWings(); quackBehavior = new Quack(); } public override void Display() { Console.WriteLine("我是一只绿头鸭!"); } }/// <summary>
/// 模型鸭 /// </summary> public class ModelDuck:Duck { public ModelDuck() { flyBehavior = new FlyNoWay(); quackBehavior = new MuteQuack(); } public override void Display() { Console.WriteLine("我是一个模型鸭"); } } static void Main(string[] args) { Duck muteQuack = new MallardDuck();muteQuack.PerformFly();
Duck model = new ModelDuck();
model.PerformFly(); model.setFlyBehavior(new FlyRocketPower()); model.PerformFly(); Console.ReadLine(); }
转载请注明来自:闪闪的幸运星
原文地址:
如若转载,请保留原文地址。谢谢合作。