考慮下面的代碼。通過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