单例模式

来源:互联网 发布:网络抓包软件debugger 编辑:程序博客网 时间:2024/06/13 22:48

题目:实现一个类,只能生成该类的一个实例

Release()函数:防止内存泄露;
私有的构造函数:生成唯一的一个实例;
私有的拷贝构造函数、私有的赋值操作符函数的申明:不违背单例模式的特性;

GetInstance()函数:公有的静态方法去获取唯一的实例--------------->static关键字确保全局的唯一性;
要使用多线程会出现问题:则需要增加互斥锁lock(),unlock();互斥锁需自己去实现;
由于每次去上锁、开锁会有很大的系统开销问题,则在用if(instance == NULL)语句去判断,只有当对象没被创建之前才去上锁,反之不上锁;

static Singleton* instance;:私有的静态指针变量指向类的唯一实例,static关键字使得其与类关联在一起;

Singleton* Singleton:: instance = NULL;:静态数据成员必须在类的外部定义和初始化;且定义时不能重复static关键字,该关键字只出现在类内部的申明语句;

代码如下:

class Singleton{private:static Singleton* instance;private:Singleton(){}Singleton(const Singleton& sl);Singleton& operator=(const Singleton& sl);public:static void Release(){if (instance != NULL){delete[] instance;instance = NULL;}}static Singleton* GetInstance(){if (instance == NULL){Lock();if (instance == NULL){instance = new Singleton();}Unlock();}return instance;}};Singleton* Singleton:: instance = NULL;




1 0