gpt4 book ai didi

c++ - 策略模式与继承

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:06:56 26 4
gpt4 key购买 nike

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

  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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com