让我们有一个简单的Decorator示例:
struct IStuff {
virtual void Info()=0;
virtual ~IStuff() { }
};
class Ugly : public IStuff {
public:
void Info() { cout << "Ugly"; }
};
class Shiny : public IStuff {
IStuff* stuff;
public:
Shiny(IStuff* stuff) {
this->stuff = stuff;
}
~Shiny() {
delete stuff;
}
void Info() {
stuff->Info(); // <------------------------------- call super?
cout << "->Shiny";
}
};
int main() {
IStuff* s = new Ugly();
s = new Shiny(s); // decorate
s = new Shiny(s); // decorate more
s->Info(); // Ugly->Shiny->Shiny
delete s;
return 0;
}
这也是Call super反模式吗?
Call super是一种设计模式,其中特定类规定在派生子类中,用户需要覆盖方法并在特定点回调重写函数本身。
这是little different implementation设计有什么不同吗?
答案 0 :(得分:6)
这不是Call super。您调用另一个Info
实例的IStuff
方法,而不是覆盖版本。
调用超级版本:
struct IStuff {
// If you override this, you MUST call the base class version <-- call super
virtual void Info()
{
// a default implementation.
std::cout << "Super call ";
}
virtual ~IStuff() { }
};
class Shiny : public IStuff {
public:
void Info() {
IStuff::Info(); // don't forget to call base implementation.
std::cout << "->Shiny";
}
};
Decorator的一些实现正在对Decorator基类进行超级调用,它负责保存,调用和管理修饰的引用:
struct IStuff
{
virtual void Info() = 0;
virtual ~IStuff() { }
};
class Stuff : public IStuff
{
public:
void Info() { std::cout << "Basic stuff"; }
};
class StuffDecorator : public IStuff
{
IStuff* decorated_;
public:
StuffDecorator(IStuff* decoratedStuff) :
decorated_(decoratedStuff) {}
~StuffDecorator() { delete decorated_; }
void Info()
{
decorated_->Info();
}
};
class Shiny : public StuffDecorator
{
public:
Shiny(IStuff* stuff) : StuffDecorator(stuff) { }
void Info()
{
StuffDecorator::Info();
std::cout << "->Shiny";
}
};
为了避免超级调用,您可能希望将Decorator与Template Method结合使用:
class StuffDecorator : public IStuff
{
IStuff* decorated_;
public:
StuffDecorator(IStuff* decoratedStuff) :
decorated_(decoratedStuff) {}
~StuffDecorator() { delete decorated_; }
void Info()
{
decorated_->Info();
DoInfo();
}
private:
// Template method
virtual void DoInfo() = 0;
};
class Shiny : public StuffDecorator
{
public:
Shiny(IStuff* stuff) : StuffDecorator(stuff) { }
private:
void DoInfo()
{
std::cout << "->Shiny";
}
};