今天看了一篇文章,学习了cocos2d-x下的观察者模式,觉得受益匪浅,观察者模式就是发送一个消息,让观察者执行某个动作,可用于数据传递,以可以用于消息传递
1.在同个层里面的观察者模式,用HelloWorld做为示例:
在HelloWorld.h里面需要写HelloWorld的虚构函数,用于观察者的释放内存,因为观察者相当于一个单例,再写一个回调函数,处理观察者做的事情
HelloWorld.h
void ObserverFunction(Ref * ref);
~HelloWorld();
在HelloWorld.cpp的init()方法中写上
NotificationCenter::getInstance()->addObserver(this, CC_CALLFUNCO_SELECTOR(HelloWorld::ObserverFunction), "message", NULL);
添加观察者,参数1为事件监听的目标,参数2为回调函数(即接收到消息后执行的函数),参数3为消息名,参数4为消息体。
在HelloWorld::~HelloWorld()方法中写上
NotificationCenter::getInstance()->removeObserver(this, "message");
在menuButton按钮的回调函数写上
NotificationCenter::getInstance()->postNotification("message", NULL);
发送消息,让观察者知道,调用ObserverFunction函数。
假如
void HelloWorld::ObserverFunction(Ref *ref)
{
log("You Click menuButton");
}
点击按钮会有如下效果:
2.在不同层里面的观察者模式,用SecondLayer做为示例:
在SecondLayer.h里面需要写SecondLayer的虚构函数,用于观察者的释放内存,因为观察者相当于一个单例,再写一个回调函数,处理观察者做的事情
SecondLayer.h
void ObserverFunction(Ref * ref);
~SecondLayer();
在SecondLayer.cpp的init()方法中写上
NotificationCenter::getInstance()->addObserver(this, CC_CALLFUNCO_SELECTOR(SecondLayer::ObserverFunction), "message", NULL);
添加观察者,参数1为事件监听的目标,参数2为回调函数(即接收到消息后执行的函数),参数3为消息名,参数4为消息体。
在SecondLayer::~ SecondLayer()方法中写上
NotificationCenter::getInstance()->removeObserver(this, "message");
在HelloWorld在menuButton按钮的回调函数写上
int num=CCRANDOM_0_1()*1000;//0-1000的随机数
NotificationCenter::getInstance()->postNotification("message",(Ref*)new __Integer(num));//向观察者传递数据
发送消息,让观察者知道,调用ObserverFunction函数,其中int转换成Ref可以(Ref*)new __Integer(num)写。
假如
void HelloWorld::ObserverFunction(Ref *ref)
{
log("SecondLayer Receive num=%d", dynamic_cast<__Integer*>(num)->getValue());
}
Ref转换成int:
dynamic_cast<__Integer*>(num)->getValue()
点击按钮会有如下效果: