c++ - 试图掌握动态层次类关系的装饰器设计

标签 c++ class decorator hierarchy

我正在尝试学习装饰器设计,我想出了一些很棒的东西,但我不知道我的想法是否会被编译。所以我创建了一些类:

这是基类

class parameter
{
public:
    parameter(){}
    parameter(double mini, double maxi, double def) :
    mini(mini),
    maxi(maxi),
    def(def)
    {}
    double mini, maxi, def;
    double val;
    virtual double getValue() { return val; }
    virtual void setValue(double v) { val = v; }
};

此类存储 smoothedParameters。 smoothedParameter 会在需要平滑时将自身添加到 SmootherManager 中,并在平滑完成后自行移除。

class SmootherManager
{
public:
    SmootherManager() {}
    juce::Array<smoothedParameter *> CurSmoothingList;
    void add(smoothedParameter * sp)
    {
        CurSmoothingList.addIfNotAlreadyThere(sp);
    }

    void remove(smoothedParameter * sp)
    {
        CurSmoothingList.removeFirstMatchingValue(sp);
    }

    void doSmoothing()
    {
        for (auto & sp : CurSmoothingList)
            sp->incValue();
    }
};

此类随时间获取值并输出平滑值。

    class smoothedParameter : public parameter
    {
    public:
        //smoothedParameter(){}
        smoothedParameter(double smoothingSpeed, SmootherManager & manager, parameter * p) :
            smoothingSpeed(smoothingSpeed),
            manager(manager),
            p(p)
        {}

        double smoothingSpeed;
        SmootherManager & manager;
        parameter * p;

        rosic::ExponentialSmoother smoother;

        double getValue()
        {
            return smoother.getCurrentValue();
        }
        void setValue(double v)
        {
            p->setValue(v);
            smoother.setTargetValue(p->getValue());
            if (!smoother.finishedSmoothing())
                manager.add(this);
        }
        void incValue()
        {
            smoother.getSample();
            if (smoother.finishedSmoothing())
                manager.remove(this);
        }
    };

此类获取一个值并通过修饰符列表随时间修改它。

class modulatedParameter : public parameter
{
public:
    modulatedParameter(parameter * p) : p(p) {}
    juce::Array<modifier *> modulationInputs;
    parameter * p;
    double getValue()
    {
        double totalMod = 0;
        for (const auto & m : modulationInputs)
            totalMod += m->val;

        return totalMod * p->getValue();
    }
    void setValue(double v)
    {
        p->setValue(v);
    }
    void add(modifier * sp)
    {
        modulationInputs.addIfNotAlreadyThere(sp);
    }
    void remove(modifier * sp)
    {
        modulationInputs.removeFirstMatchingValue(sp);
    }
};

这就是它的工作原理。你有一个平滑器和一个调制器。如果你在调制器内部构造一个平滑器,你就会得到一个平滑的调制器。如果您在平滑器内构建调制器,您将得到一个非平滑调制器。

下面是我想如何使用这些类:

// create the smoother manager
SmootherManager smManager;

// create modulatable parameter
auto mp = new modulatedParameter(new parameter(0.0, 1.0, 0.0));

// create a smoothable parameter
auto sp = new smoothedParameter(0.01, smManager, new parameter(0.0, 1.0, 0.0));

// create a modulatable parameter where its modifiers are smoothed
auto mp_sp = new modulatedParameter(new smoothedParameter(0.01, smManager, new parameter(0.0, 1.0, 0.0)));

// create a parameter where values are smoothed, but the modulation is not
auto sp_mp = new smoothedParameter(0.01, smManager, modulatedParameter(new parameter(0.0, 1.0, 0.0)));

好的!问题来了。

modifier myMod;

// add a modifier to sp_mp, can't do it, sp_mp has no add function.
sp_mp->add(&myMod);

我正在尝试向 smoothedParameter 的 modulatedParameter 添加调制器。我想了一个办法,但这好像不对。

auto mp = new modulatedParameter(sp_mp->p);
mp->add(&myMod)
sp_mp = new smoothedParameter(0.01, smManager, mp));
任何时候我想添加/删除修饰符,我都必须经过几个步骤。我可以想出一种方法来解决这个问题,但我对什么是实用方法一无所知,因为我不知道 C++ 的所有可能性。装饰器设计的要点是对象可以具有一组不同的功能。 ...似乎我需要为每个类都有一个“添加/删除”功能,这违背了这个设计的目的。

最佳答案

The point of decorator design is that objects can have a different set of functions.

不,装饰器的意义在于能够灵活地扩展对象的基本功能,同时保留其核心。通常,“灵活”一词假定在运行时(动态地)进行此扩展。

同时,C++ 是静态类型语言。这意味着对象/变量的类型定义了您可以对它做什么以及您不能做什么。 sp_mp->add(&myMod); 变量 sp_mp 的可能的 IIF 类型(类)有 add(...) 功能。这个决定是在编译时做出的,没有设计模式可以改变这个事实,只是接受它。 C++ 编译器不会让您调用函数/使用不属于其类型的变量的成员变量。 无论你做什么,现有类型的接口(interface)都是静态定义的。想改变它吗?在编译时执行。

现在,考虑到所说的一切,我们可以得出一个合乎逻辑的结论:
如果您想向现有类型添加一些新功能 - 创建一个新类型。

这是一个或多或少经典的(我相信)装饰器实现。
*我没有使用共享指针只是因为... OP 也没有使用它们:)

class ICore
{
public:
    virtual std::string Description() = 0;

    void Describe() {
        std::cout << "I am " << Description() << std::endl;
    }
};

class Core final : public ICore
{
public:
    std::string Description() override {
        return "Core";
    }
};

class IDecorator : public ICore
{
protected:
    ICore* core;

public:
    IDecorator(ICore* _core)
        : core{ _core }
    { }

    virtual ~IDecorator() {
        delete core;
    }
};

class Beautiful final : public IDecorator
{
public:
    Beautiful(ICore* _core)
        : IDecorator{ _core }
    { }

public:
    std::string Description() override {
        return "Beautiful " + core->Description();
    }
};

class Shiny final : public IDecorator
{
public:
    Shiny(ICore* _core)
        : IDecorator{ _core }
    { }

public:
    std::string Description() override {
        return "Shiny " + core->Description();
    }
};


int main()
{
    ICore* core = new Core;
    ICore* decorated_core = new Beautiful{ new Shiny{ core } };

    core->Describe();
    decorated_core->Describe();

    delete decorated_core;

    return 0;
}

输出:

I am Core
I am beautiful shiny Core

如您所见,这里的 Decorator 没有更改接口(interface)(类原型(prototype))——没有向核心添加新功能。此外,它没有更改任何现有功能。然而,它所做的是对已经存在的行为的扩展。它用 2 个新词从字面上装饰核心的描述。请注意 - 此装饰发生在运行时。如果我们决定将修饰顺序从 new Beautiful{new Shiny{core}} 更改为 new Shiny{new Beautiful{core}} 词序也会改变(从beautiful shiny Coreshiny beautiful Core).


但是,如果您真的-真的想要实现您的主要目的 - 使用装饰器添加一个全新的功能......有一种方法可以让您模仿这种行为。它在 C++14 中看起来很难看,所以这里是 C++17 代码:

class Core
{
public:
    void CoreFunctional() {
        std::cout << "Core functional." << std::endl;
    }
};

template<typename T>
class Extend : public virtual T
{
public:
    Extend() = default;
    Extend(const T&) {  }

public:
    void ExtendedFunctional() {
        std::cout << "Extended functional." << std::endl;
    }
};

template<typename T>
class Utility : public virtual T
{
public:
    Utility() = default;
    Utility(const T&) {  }

public:
    void UtilityFunctional() {
        std::cout << "Utility functional." << std::endl;
    }
};


int main()
{
    Core core;
    core.CoreFunctional();

    auto decorated_core = Utility{Extend{core}};
    decorated_core.CoreFunctional();
    decorated_core.ExtendedFunctional();
    decorated_core.UtilityFunctional();
}

输出正如您所期望的那样,但我不太确定,是否可以将其视为装饰器...

关于c++ - 试图掌握动态层次类关系的装饰器设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46006585/

相关文章:

c++ - linux下计算周期数

javascript - 使用 Mootools 理解类

class - 同一类的两个对象之间的碰撞

Python 函数装饰器应该打印完整的方法名称

python - Flask:为什么 app.route() 装饰器应该总是在最外面?

python - 使用装饰器

c++ - 将纹理渲染到窗口

c++ - 允许 tr1::function 吞下返回值的解决方法

c++ - 使用 Visual Studio-commander 配置 Qt 4.7.3 失败(返回 #2)

java - 实例化可以是具体类或接口(interface)类的 Java 类