cocos设计模式之单例设计模式
在Cocos2d-x中存在不少的单例,虽然单例的设计模式引起不少弊端。我们使用单例目的就是获得全局的唯一一个对象,来做一些事情,那么什么时候用单例什么时候不用单例呢。
我觉得一个是从道理上来说,单例在全局应该是唯一的,比如cocos2dx中的导演类,一个游戏应该只有一个导演去完成一些功能,还有就是当你需要在一个类中初始化一个需要设定为单例的对象,为这个对象的成员变量赋值,当在另一类中的时候,我们需要取得这个对象中的成员变量的值的时候,这样就设计成单例的,虽然通过其他的方法也可以完成任务,我觉得设计成单例还是比较方便的,下面给出单例的模板。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
/************************************************************************/ /* 单例模版 */ /************************************************************************/ #ifndef _SINGLETON_H_ #define _SINGLETON_H_ template < class T> class Singleton { private : //该变量中存放这个全局的变量 static T * iInstance; //将构造函数私有或者是保护 protected : Singleton(){}; public : //获得单例对象 static T * getInstance(); //释放单例对象 static void FreeInstance(); }; template < class T> T * Singleton<T>::iInstance=NULL; template < class T> T * Singleton<T>::getInstance() { if (iInstance == 0) { iInstance= new T(); } return iInstance; } template < class T> void Singleton<T>::FreeInstance() { if (iInstance) { delete iInstance; iInstance=NULL; } } #endif |
如上的这种写法在程序中的时候你可以用具体的数据类型来代替,但是思路需要按照模板提供的这个思路来写。如果你的程序中有多个类想要设置为单例类,而同样的代码不想重复编写,我们就需要继承这个模板类,然后做一些操作,下面给出我在摸索过程中的一种方法,这种方法是不能完成任务的,但是你可以知道为什么会引出最终的那种方法了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#include "Singleton.h" //该类继承自模板单例类 class MyClass : public Singleton<MyClass> { private : //添加这个类自己的一些成员变量 int age; //这里将构造函数私有,防止产生其他的对象,有些人没有将构造函数私有以为c++中成员的默认访问权限是private //所以就不写出构造函数了,然后在其他类中使用单例类的函数,其实如果你声明一个对象的时候就会发现可以声明 //对象,这样的话就没有做到真正的单例。c++中成员的默认访问权限是private不假,但是当我们没有默认的构造函数 //的时候系统会为我们产生一个构造函数,这个构造函数是public的 MyClass(){}; public : //添加一些其他的方法 void setAge( int age){ this ->age = age;}; int getAge(){ return age;}; }; MyClass::getInstance()->setAge(10); cout<<MyClass::getInstance()->getAge()<<endl; //将构造函数私有所以这里不能声明对象 //MyClass my; |
程序运行的时候出错了,因为我们将MyClass的构造函数私有了,在单例模板类中,iInstance=new T();这句话是无法通过的,因为在一个类外是无法访问该类的私有成员的。如果我们将MyClass的构造函数声明为public的,则类外也就可以声明对象了,这和单例的初衷又相悖了。所以利用c++的知识,我们需要将这个单例模板类声明为MyClass类的友元类,这样的话就可以做到了,现在我将MyClass类改为Test类,实现的代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#include <iostream> #include "Singleton.h" using namespace std; //Test类继承自单例模板类 class Test : public Singleton<Test> { //将单例模板类声明为Test类的友元类 friend class Singleton<Test>; //将构造函数私有 private : Test(){}; //这里添加test类的其他一些成员 int age; //这里添加test类的其他一些成员 public : void setAge( int age){ this ->age = age;}; int getAge(){ return age;}; }; //将构造函数私有所以这里不能声明对象 //Test t; Test::getInstance()->setAge(30); cout<<Test::getInstance()->getAge()<<endl; |

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~