Singleton就是保證一個類只有一個實例,在Ogre里面有很多Singleton的例子,幾乎所有的Manager都是Singleton的實例。比較下Gof里面的Singleton的實現和loki中的Singleton的實現,Ogre的Singleton算是比較簡單的。Gof中實現一般是把類的構造函數給Private了然后再加上static的變量和函數實現的。下面來具體看一下Ogre中的Singleton
#include <iostream>
#include "singleton.h"
class Intsin:public Singleton< Intsin >


{
public:

Intsin(int tmp):t(tmp)
{std::cout << "build"<< std::endl;}

~Intsin()
{std::cout << "destory"<< std::endl;}

print()
{std::cout << t << std::endl;}
private:
int t;
};

template<> Intsin* Singleton< Intsin > ::ms_Singleton = 0;

int main()


{
Intsin* a;
a = new Intsin(3);
a->print();
delete a;
system("pause");
}
上面是一個超簡單的實現,主要來看一下a = new Intsin(3);這里系統先按照Intsin的大小分配一塊內存出來,然后調用Intsin的構造函數,當然要先運行基類Singleton<Intsin>的構造函數,這時Singleton構造函數的this指針應該是指向剛才分配的那個Intsin對象的地址了,雖然里面的東西不完整,但是this指向的對象的基本框架已經有了。所以可以這樣使用它。要想知道這時this指針指向的對象到底有什么東西,什么東西沒有,可以搜索一下“構造函數的this”看一下有關文章。當構造函數完成的時候,new返回一個指針。這樣就完成了一個實例了。
下面來說一下,這個類什么東西沒做,用的時候要注意什么。
1.當要實例化一個已經被實例化的類時,會有assert(!ms_Singleton);所以一定不能這樣做。
2.對一個實例的指針兩次調用delete也是讓程序崩潰的好辦法
3.Singleton<>不負責對象的解析,所以一定要記得自己delete,記住就一次。
總結下,這里的Singleton的實現比較簡單,也很好用,但是程序員要負責的東西比較多。在Ogre中幾乎所有的Singleton對象都是在root里面new和delete的。
就這么多吧。
1
#ifndef _SINGLETON_H__
2
#define _SINGLETON_H__
3
4
namespace Ogre
{
5
template <typename T> class Singleton
6
{
7
protected:
8
static T* ms_Singleton;
9
public:
10
Singleton( void )
11
{
12
assert( !ms_Singleton );
13
#if defined( _MSC_VER ) && _MSC_VER < 1200
14
int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;
15
ms_Singleton = (T*)((int)this + offset);
16
#else
17
ms_Singleton = static_cast< T* >( this );
18
#endif
19
}
20
~Singleton( void )
21
{ assert( ms_Singleton ); ms_Singleton = 0; }
22
static T& getSingleton( void )
23
{ assert( ms_Singleton ); return ( *ms_Singleton ); }
24
static T* getSingletonPtr( void )
25
{ return ms_Singleton; }
26
};
27
}
28
#endif

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

先來看一下Singleton的構造函數是Public的,這樣不是大家都能用了?往下看,第一句就是assert(!ms_Singleton); 如果ms_Singleton不是0的話,也就是Singleton<T>已經有了一個自己的對象,那么程序就死翹翹了。如果是0,那么跳過13-16行,直接看17行的
ms_Singleton = static_cast<T*>(this),有沒有注意到那個this,出現在這里有點詭異。這里是構造函數,對象的初始化還沒有完成呢,那么this指向的東西是什么呢?先來看一下怎么生成一個Singleton的實例。
































下面來說一下,這個類什么東西沒做,用的時候要注意什么。
1.當要實例化一個已經被實例化的類時,會有assert(!ms_Singleton);所以一定不能這樣做。
2.對一個實例的指針兩次調用delete也是讓程序崩潰的好辦法
3.Singleton<>不負責對象的解析,所以一定要記得自己delete,記住就一次。
總結下,這里的Singleton的實現比較簡單,也很好用,但是程序員要負責的東西比較多。在Ogre中幾乎所有的Singleton對象都是在root里面new和delete的。
就這么多吧。