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/

相关文章:

java - 创建自定义覆盖方法问题

asp.net-mvc-3 - 如何将 asp.net MVC 脚手架与从 dbcontext 向下两个子类的上下文一起使用

c++ - 在派生类上将 std::make_unique 与自定义删除器一起使用?

c++ - C++ 20比较: warning about ambiguous reversed operator

c++ - 函数不会更改 C++ 中的对象属性

c#-4.0 - 使用动态关键字调用子类方法

c++ - 具有不同模板参数的继承

c++ - Windows 10 上的 Code::blocks 弹窗

java - C++ 全局变量与 Java 实例变量

php - 在php中获取父类的所有定义类