Is a decorator template the right choice here?

Consider the code below. Through A::doit()it is assumed that the object Bmust increase the total value by 3. The object Decorated1must increase the total value by 4, and the object Decorated2must increase the total value by 5. The object A, which is a combination of these derived types, must still perform its “special actions”, but should increase the total value by max (not the sum) individual increase as a whole. But the decorator pattern gets the amount instead of max. Should I leave the Decorator template here?

#include <iostream>

int total = 0;

struct A {
public:
    virtual void doIt() = 0;
};

struct Decorator : public A {
    A* a;
    Decorator (A* a_) : a(a_) {}
    virtual void doIt() override {a->doIt();}
};

struct B : public A {
    virtual void doIt() override {
        total += 3;
        std::cout << "Special actions by B carried out.\n";
    }
};

struct Decorated1 : public Decorator {
    using Decorator::Decorator;
    virtual void doIt() override {
        Decorator::doIt();
        total += 4;
        std::cout << "Special actions by Decorated1 carried out.\n";
    }
};

struct Decorated2 : public Decorator {
    using Decorator::Decorator;
    virtual void doIt() override {
        Decorator::doIt();
        total += 5;
        std::cout << "Special actions by Decorated2 carried out.\n";
    }
};

int main() {
    A* decorated1_2 = new Decorated2(new Decorated1(new B));
    decorated1_2->doIt();
    std::cout << "total = " << total << std::endl;
}

Conclusion:

Special actions by B carried out.  // Good I want this.
Special actions by Decorated1 carried out.  // Good I want this.
Special actions by Decorated2 carried out.  // Good I want this.
total = 12  // No, it is supposed to be 5, not the sum 3+4+5.
+4
source share
3 answers

- , .

, 12 ( B < 3 → + 1 < 4 → + 2, < 5 → ).

, , A ..

, .

- Creation

java-. https://github.com/pavansn/java-design-patterns

,

+5

doIt . - , .

. .

  • .
+2

, , , , , , , -

Struct A 0
Struct B 3
Struct Decorator1 7 (3 + 4)
Struct Decorator2 12 (3 + 4 + 5)

, , .

+2

Source: https://habr.com/ru/post/1589459/


All Articles