这不是呼叫超级。您调用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";
}
};