Cocos2d-x中的观察者模式

游戏开发中往往会遇到数据的及时更新,层间通信等问题,例如游戏中花费金币购买道具,完成后需要及时更新状态栏的个人金币信息。Cocos2d-x给我们提供了一种解决方案,这就是使用观察者模式,CCNotificationCenter是一个单例类。使用的方式很简单,在初始化时可以添加一个观察者

CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(ObserverModel::receiveMsg), "Update", NULL);
然后在需要发消息的地方post就可以CCNotificationCenter::sharedNotificationCenter()->postNotification("Update");
添加观察者的函数包括四个参数,第二个参数即设置消息的回调函数,第三个参数可以理解为观察者的标识,这个和post的消息名称一样。
发送消息包括两种方式,带数据和不带数据
void postNotification(const char *name);
void postNotification(const char *name, CCObject *object);
使用观察者模式结束时一定要移除观察者,以免出现内存泄露。
本例中通过点击按钮,显示一串字符,实现消息通知,每次点击显示的字符颜色会发生变化。

 1 void ObserverModel::onEnter()
 2 {
 3     CCLayer::onEnter();
 4     CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(ObserverModel::receiveMsg), "Update", NULL);
 5 }
 6 
 7 void ObserverModel::sendMsg()
 8 {
 9     SendMessage* msg=SendMessage::create();
10     this->addChild(msg);
11 }
12 
13 void ObserverModel::receiveMsg()//改变文字颜色
14 {
15     srandom(time(NULL));
16     int r=random()%225;
17     int g=random()%225;
18     int b=random()%225;
19     label->setString("Messages come to here!");
20     label->setColor(ccc3(r, g, b));
21 }
22 
23 void ObserverModel::onExit()
24 {
25     CCNotificationCenter::sharedNotificationCenter()->removeObserver(this, "Update");
26     CCLayer::onExit();
27 }
28 
29 
30 bool SendMessage::init()//post message
31 {
32     if(!CCLayer::init())
33     {
34         return false;
35     }
36     CCNotificationCenter::sharedNotificationCenter()->postNotification("Update");
37     
38     return true;
39 }

 

posted @ 2014-02-13 11:17  【Winco】  阅读(733)  评论(0编辑  收藏  举报