首页 > 其他 > 详细

设计模式 策略模式

时间:2015-01-26 22:32:40      阅读:329      评论:0      收藏:0      [点我收藏+]

策略模式(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

 

设计模式 策略模式

原文:http://www.cnblogs.com/YuanSong/p/4251430.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!