策略模式(Strategy Pattern)

本文介绍了策略模式的概念及其在软件设计中的应用。策略模式定义了一系列可互换的算法,并封装每个算法以便于更换。文章通过示例代码展示了如何实现策略模式,并讨论了其优缺点。

摘自:

策略模式(Strategy):它定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策 略模式让算法的变化不会影响到使用算法的客户。(原文:The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.)

 

 

图1 策略模式类图

 优点:

  1、 简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试。
  2、 避免程序中使用多重条件转移语句,使系统更灵活,并易于扩展。
      3、 遵守大部分GRASP原则和常用设计原则,高内聚、低偶合。

  缺点:
  1、 因为每个具体策略类都会产生一个新类,所以会增加系统需要维护的类的数量。
      2、 在基本的策略模式中,选择所用具体实现的职责由客户端对象承担,并转给策略模式的Context对象。(这本身没有解除客户端需要选择判断的压力,而策略 模式与简单工厂模式结合后,选择具体实现的职责也可以由Context来承担,这就最大化的减轻了客户端的压力。

代码:

    public abstract class Strategy
    {
        public abstract void strategyInterface();
    }

    public class ConcreteStrategy : Strategy
    {
        public override void strategyInterface()
        {
            Console.Write("ConcreteStrategy strategyInterface");
        } 
    }

    public class Context
    {
        private Strategy strategy = null;
        public Context(Strategy strtegy)
        {
            this.strategy = strategy;
        }
        public void contextInterface()
        {
            this.strategy.strategyInterface();
        }
    }

调用:

  Context context = new Context(new ConcreteStrategy());
  context.contextInterface();

 

转载于:https://www.cnblogs.com/nygfcn1234/p/3406849.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值