1

让我们有一个简单的装饰器示例:

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 超级反模式吗?

Call super 是一种设计模式,其中特定类规定在派生的子类中,用户需要覆盖方法并在特定点回调被覆盖的函数本身。

这里有一点不同的实现设计有什么不同吗?

4

1 回答 1

6

这不是呼叫超级。您调用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";
  }
};
于 2012-08-26T14:11:26.057 回答