在c++中实现回调的最好方法是什么?
What would be the best way to implement callback in C++
我对学习别人如何设计他们的软件很感兴趣。我在不同的项目中使用了不同的解决方案,但我觉得我可以做得更好。我的实现涉及到委托和观察者的使用,但是今天我忍不住问你,你会怎么写它。
让我们假设我们有以下内容:
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_)?
谢谢
我会使用函数指针或函数对象:
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();
}
};
请参阅设计模式:发布者/使用者、发布者/订阅者。
我会看看Boost Signals也像Piotr s建议。此外,我使用的一个简单模式在您的例子中看起来像这样:
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
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- 在 c++ 中拥有一组结构的正确方法是什么?
- 通过JNI传递数据数组的最快方法是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在另一个类视图中添加最多2个图表的正确方法是什么
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 在C++中包含原型文件的正确方法是什么?
- 在 OpenCV C++ 中估计基本矩阵之前对相应点进行归一化的正确方法是什么?
- 在PostgreSQL中根据它们的ID选择大量行的最快方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 将一系列整数放入类的最佳方法是什么?
- 从长整整转换为uint64_t的推荐方法是什么?
- 将此布尔值传递给此函数的最有效方法是什么?
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?