zoukankan      html  css  js  c++  java
  • 设计模式--策略模式C++实现

    策略模式C++实现

    1定义

    (Strategy Pattern)定义一组算法,将每个算法都封装起来,并且使他们可以相互替换

    也叫政策模式

    2类图

    3实现

    class Strategy
    {

    protected:

      Strategy();

    public:

      virtual ~Strategy() = 0;

      virtual void doSomething()=0;

    };

    class ConcreteStrategy1:public Strategy

    {

    public:

      void doSomething()

      {

        cout << "具体策略1的运算法则"<<endl;

      }

    };

    class ConcreteStrategy2:public Strategy

    {

    public:

      void doSomething()

      {

        cout << "具体策略1的运算法则"<<endl;

      }

    };

    //封装角色

    class Context

    {

    private:

      Strategy * _str;

    public:

      Context(Strategy * st)

        :_str(st)

      {}

      void doAnything()

      {

        _str->doSomething();  

      }

    };

    void Test

    {

      Strategy * st = new ConcreteStrategy1();

      Context *con = new Context(st);

      con->doAnything();

    }

    4应用

    ①优点

    算法可以自由切换

    避免使用多重条件判断.将决策权转接给高层,你传入策略我执行该就可以

    扩展性良好

    ②缺点

    策略数量增多

    所有的策略类都会暴漏在外,上层必须知道具体策略

    注:这个缺点是可以通过其他方式进行弥补的eg工厂方法,代理模式,享元模式

    5使用场景

    多个类只有在算法上稍有不同

    算法需要自由切换

    需要屏蔽算法规则的地方。(仿函数类似)

    注意事项,一个策略家族的具体策略数量不得超过4个,否则使用混合模式解决策略类膨胀和对外暴漏的问题。

    6扩展

    枚举策略

    定义:它是一个枚举,浓缩了策略模式的枚举

    枚举特性:pubic,finaly,static

    所以在C++中其实就是一个一个类封装多个静态方法。(一半用作不经常改变的角色)

    eg  Strategy::ADD();

      Strategy::Sub();....

  • 相关阅读:
    ②.kubernetes service
    c2p
    ⑤.docker dockerfile
    ④.docker volume
    ②.docker image
    ③.docker container
    ①.docker介绍
    三剑客之grep
    ⑦.shell 数组
    shell 正则
  • 原文地址:https://www.cnblogs.com/lang5230/p/5328508.html
Copyright © 2011-2022 走看看