假设我有这些类(class) View A和 View B
在使用委托(delegate)模式的 objective-c 中我可以做到
@protocol ViewBDelegate{
- (void) doSomething();
}
然后在ViewB界面:
id<ViewBDelegate> delegate;
然后在 ViewA 实现中我设置了委托(delegate):
viewB.delegate = self;
现在我可以从 viewB 调用 doSomething 到任何未知类型的委托(delegate)上。
[delegate doSomething];
“C++ 如何编程”读起来很糟糕,找不到演示基本设计模式的简单示例。
我在 C++ 中寻找的是:
- 事件 ActionScript 和 java
- 或 Objective C 中的委托(delegate)或 NSNotifications
任何允许 A 类、B 类和 C 类知道 ClassX didSomething()!!!
谢谢
最佳答案
如果我是你,我不会使用函数指针来完成这个任务。将此选项留给专家 ;)
在 Boost 中,有一个漂亮的库叫做 signals .它让您的生活更轻松!这是一个用法示例:
#include <iostream>
#include <boost/bind.hpp>
#include <boost/signal.hpp>
using namespace std;
using namespace boost;
struct A
{ void A_action() { cout << "A::A_action();" << endl; } };
struct B
{ void B_action() { cout << "B::B_action();" << endl; } };
struct C
{ void C_action() { cout << "C::C_action();" << endl; } };
struct X
{
// Put all the functions you want to notify!
signal<void()> list_of_actions;
void do_something()
{
std::cout << "Hello I am X!" << endl;
list_of_actions(); // send notifications to all functions in the list!
}
};
int main()
{
X x;
A a;
B b;
C c;
x.list_of_actions.connect(bind(&A::A_action, a));
x.list_of_actions.connect(bind(&B::B_action, b));
x.list_of_actions.connect(bind(&C::C_action, c));
x.do_something();
}
这将打印:
Hello I am X!
A::A_action();
B::B_action();
C::C_action();
这是它的工作原理。
首先,声明代表的位置:
signal<void()> list_of_actions;
然后,您将它“连接”到您想要调用的任何一组函数/仿函数/可调用对象。
x.list_of_actions.connect(bind(&A::A_action, a));
x.list_of_actions.connect(bind(&B::B_action, b));
x.list_of_actions.connect(bind(&C::C_action, c));
注意,我使用了bind
。因此,list_of_actions 中的函数类型是相同的,但我们可以将它连接到不同类型的类。所以:
bind(&A::A_action, a)
这个东西,产生一个可调用的东西,类型为 void ()
,因为我们之前声明了 list_of actions
的类型。当然,您可以在第二个参数中指定要应用此成员函数的实例。
如果你正在做多线程的东西,那么使用它的姐妹signals2 .
希望对您有所帮助。
关于c++ - 在 C++ 中是否有任何事件/委托(delegate)/接口(interface)/通知!任何事物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3031649/