考虑下面的代码。通过A::doit()
,B
对象应该总计增加3.一个Decorated1
对象应该总计增加4个, 和一个Decorated2
对象应该总数增加5.一个A
对象是这些派生类型的组合仍然执行他们的“特殊行动”,但是是通过个人增加总额的最大值(而非总和)来增加总额。但装饰者模式是获得总和而不是最大值。我必须在这里放弃Decorator模式吗?Decorator模式是否适合您?
#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;
}
输出:
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.
'Decorator'不应该从'A'继承,否则它不是一个装饰器...... – Barry
另外,它是如何让所有的输出语句运行,但不是所有的'total + ='? – Barry
@Barry。我希望在这里有一些解决方法,我得到所有的输出语句,但只提取最大值。 – prestokeys