当前位置:编程学习 > wap >>

cocos2d-x中的单例模式运用

单例模式是什么我就不赘述了,直接进入正题。
 
我们在C++往往能用到单例模式,但在cocos2d-x中,运用单例模式时,您是否遇到了麻烦,各种“无法解析”,“error LNK"错误出来。
 
下面我用个例子简单介绍下单例模式在cocos2d-x是如何编写的:
 
 
这里我编写一个类Global,用来存储游戏中全局都可以访问的唯一变量,这就要求我们随时可以在任意对象中能访问Global,来读取里面存储的唯一变量
 
头文件如下:
 
[cpp]  
#ifndef _GLOBAL_H_  
#define _GLOBAL_H_  
  
#include "cocos2d.h"  
#include "StartLayer.h"  
  
class Global{  
public:  
    StartLayer* startLayer; //存储全局可以访问的唯一性变量  
    static Global* toIns(); //通过这个方法返回Global对象  
protected:  
    ~Global();  
};  
  
#endif  
 
Cpp文件如下:
[cpp]  
#include "Global.h"  
  
using namespace cocos2d;  
static Global* share=NULL; //这行非常重要,我们之前犯的错误就是C++习惯,将此变量声明和初始化放在头文件中,导致错误  
Global::~Global(void){  
    startLayer = NULL;  
}  
Global* Global::toIns(){  
    if(!share){  
        share = new Global();  
        CCLOG("first");  
    }  
    CCLOG("hello");  
    return share;  
}  
 
也可以这样做:
 
头文件如下:
 
[cpp]  
#ifndef _GLOBAL_H_  
#define _GLOBAL_H_  
  
#include "cocos2d.h"  
#include "StartLayer.h"  
  
class Global{  
public:  
    StartLayer* startLayer;  
    static Global* toIns();  
    static Global* share;  //静态变量声明在这里  
protected:  
    ~Global();  
};  
  
#endif  
 
CPP文件如下:
[cpp]  
#include "Global.h"  
  
using namespace cocos2d;  
//static Global* share=NULL;  
Global* Global::share = NULL;  //静态变量初始化放在这,而不是放在头文件中  
Global::~Global(void){  
    startLayer = NULL;  
}  
Global* Global::toIns(){  
    if(!share){  
        share = new Global();  
        CCLOG("first");  
    }  
    CCLOG("hello");  
    return share;  
}  
 
 
将代码运用到你的工程中,你学会了吗?
例外你也可以参考cocos2d-x中本身的单例(例如CCDirector)里面的代码,它们是如何实例单例的
补充:移动开发 , 其他 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,