c++ - 策略模式与继承

标签 c++ oop inheritance design-patterns strategy-pattern

我们有一些算法可以应用于某些数据,并且该算法可能会在同一数据上应用多次。我们有两种方法可以做到这一点:

  1. 保持数据和逻辑分离

    class Algo{
    public:
        virtual int execute(data_object) = 0;
    };
    
    class AlgoX: public Algo{
    public:
        int execute(data_object);
    };
    
    class AlgoY: public Algo{
    public:
        int execute(data_object);
    };
    
    class Data{
    public:
        string some_values;
        ...
        void* algo_specific_data; //It will contain some algo specific data (like state of algo)
        Algo* algo_ptr; //Reference of Algo
    
        int execute(){
            algo_ptr->execute(this);
        }
    };
    
    some_function(){
        Data* data_object = create_data(algo_ptr, algo_specific_data); //A dummy function which creates an object of type data.
        data_object->execute();
    }
    
  2. 通过继承绑定(bind)数据和逻辑

    class Data{
    public:
        string some_values;
        ...
        virtual int execute() = 0;
    };
    
    class DataWithAlgoX : public Data{
    public:
        AlgoX_Relateddata algo_related_data; //some algo specific data (like state of algo)
        int execute();
    }
    
    class DataWithAlgoY : public Data{
    public:
        AlgoY_Relateddata algo_related_data; //some algo specific data (like state of algo)
        int execute();
    }
    
    some_function(){
        Data* data_object = create_data(algo_type); //A dummy function which creates an object of type data.
        data_object->execute();
    }
    

哪种设计更好,如果

  1. 我们可以在对数据多次调用 algo->execute() 之间更改算法类型 (但切换不会很频繁,只有在某些特定场景下才需要)。
    有些人可能会指出算法的切换会使我们重新创建data_object。 如果架构 21 好得多,我们愿意承担额外的负担。

  2. 我们不会在多次调用 data 上的 algo->execute() 之间更改算法类型。

最佳答案

在同一类(class)中混合数据和算法(非常)糟糕的做法。 打破了单一责任原则。

https://en.wikipedia.org/wiki/Single_responsibility_principle

如果你想将多种类型的数据与多种算法结合起来 使用调解器之类的东西。思路是分别定义Data和Algorithms,在mediator中定义它们之间的交互。

https://en.wikipedia.org/wiki/Mediator_pattern

在我看来,设计 2 比设计 1 差得多。即使在设计 1 的情况下,我也会删除对数据类中算法的引用。它只介绍了High Coupling,i。 e.类之间的依赖关系会影响另一个类的变化:

https://en.wikipedia.org/wiki/Coupling_(computer_programming)

(和google“Low coupling, high cohesion”,这是另一个OOP原则)。

Mediator 也可以解决耦合问题。

关于c++ - 策略模式与继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48397910/

相关文章:

c++ - C++中的数组初始化

c++ - 三个数字中的最小值

c++ - c/c++ | int * 除外,给定 int (返回指针??)

c# - 构造函数链接的目的?

C++ FFTW 前向后向 DFT 值被包裹

java - 对于可以在 xml 文件中存储某些对象并读取它的类来说,合适的名称是什么?

c# - 为代码设置 ASP.NET 结构

javascript - JavaScript:对象继承自Function.prototype

C++抽象基类集合

Python数字基类或如何确定一个值是一个数字