设计模式 策略模式

策略模式(Strategy)定义了算法家族,分别封装起来,让他们之间可以相互转换,此模式让算法的变化,不会影响到使用算法的客户,即让算法独立于使用它的客户而独立变化。

策略模式由抽象策略角色(策略类,由一个接口或者抽象类实现)、具体策略角色(具体策略类,包装相关的算法和行为)、环境角色(引用策略类)。

    abstract class Strategy
    {
        //算法方法
        public abstract void AlgorithmInterface();
    }
抽象策略角色-抽象算法类
    //具体算法A
    class ConcreteStrategyA : Strategy
    {
        //算法A实现方法
        public override void AlgorithmInterface()
        {
            Console.WriteLine("算法A实现");
        }
    }
    //具体算法B
    class ConcreteStrategyB : Strategy
    {
        //算法B实现方法
        public override void AlgorithmInterface()
        {
            Console.WriteLine("算法B实现");
        }
    }
    //具体算法C
    class ConcreteStrategyC : Strategy
    {
        //算法C实现方法
        public override void AlgorithmInterface()
        {
            Console.WriteLine("算法C实现");
        }
    }
具体策略角色-具体算法类
    //上下文
    class Context
    {
        Strategy strategy;

        public Context(Strategy strategy)
        {
            this.strategy = strategy;
        }
        //上下文接口
        public void ContextInterface()
        {
            strategy.AlgorithmInterface();
        }
    }
环境角色-上下文
        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();
        }
客户端应用


策略模式与工厂模式的区别,详见博友随笔http://www.cnblogs.com/me115/p/3790615.html

 

posted on 2015-01-26 21:24  YuanSong  阅读(217)  评论(0编辑  收藏  举报

导航