【问题标题】:What would be the best way to implement callback in C++在 C++ 中实现回调的最佳方法是什么
【发布时间】:2014-08-23 04:15:24
【问题描述】:

我有兴趣了解其他人如何设计他们的软件。我在不同的项目中使用了不同的解决方案,但我觉得我可以做得更好。我的实现涉及到使用委托和观察者,但今天我忍不住问你如何编写它。

假设我们有以下内容:

class Sensor
{
  ...
  public:
    void sensorTriggered();
};

Class Device
{
  ...

  public:
    void notifyChangesFromHardware(unsigned int inNotificationInfo);

  protected:
    Sensor *fireAlarm_;
};

int main()
{
  Device someDevice;
  return 0;
}

如果你想调用“Device::notifyChangesFromHardware”,你会如何设计? 来自传感器对象 (fireAlarm_)?

谢谢

【问题讨论】:

标签: c++ design-patterns delegates


【解决方案1】:

我会使用函数指针或函数对象:

struct Notifier_Base
{
  virtual void notify(void) = 0;
};

class Sensor
{
  std::vector<Notifier_Base *> notifiers;
  void publish(void)
  {
    std::vector<Notifier_Base *>::iterator iter;
    for (iter =  notifiers.begin();
         iter != notifiers.end();
         ++iter)
    {
      (*iter)->notify();
    }
};

查看设计模式:发布者/消费者、发布者/订阅者。

【讨论】:

  • 感谢您的建议。看看其他开发人员如何解决这个问题实际上很有趣,尤其是像您这样经验丰富的高级开发人员。
【解决方案2】:

我也会像 Piotr S. 建议的那样看一下 Boost Signals。此外,在您的情况下,我使用的一个简单模式如下所示:

template<class NotifyDelegate>
class Sensor
{
  ...
  public:
    // assumes you only have one notify delegate
    Sensor( NotifyDelegate &nd ) : nd_(nd)
    {
    }

    void sensorTriggered()
    {
        unsigned int notifyInfo = 99;
        nd_.notifyChangesFromHardware( notifyInfo );
    }



  private:
    NotifyDelegate &nd_;
};



Class Device
{
  ...

  public:
    void notifyChangesFromHardware(unsigned int inNotificationInfo);

};

int main()
{
  Device someDevice;
  Sensor<Device> someSensor(someDevice);
  someSensor.sensorTriggered();

  return 0;
}

也可以看看Observer Pattern

【讨论】:

  • 感谢您的建议。了解其他人的做法非常有帮助和教育意义,当我的解决方案(我过去的解决方案)与其他开发人员的解决方案接近时,这非常令人鼓舞。
猜你喜欢
  • 2011-05-24
  • 2011-11-10
  • 1970-01-01
  • 2013-08-10
  • 2011-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多