单例类模板

单例模式:类在系统生命周期中只有一个对象存在

思路:将构造函数设为私有。创建一个标记,用于指示对象的个数,多于一个返回已经创建了的对象,少于一个则创建一个。

单例类模板的实现:

#include <iostream>
#include <string>

using namespace std;

class SObject
{
    static SObject* c_instance;  // 创建一个对象指针标记,指向GetInstance返回的对象,用于判断是否需要创建对象。    
    SObject(const SObject&);              // 将构造函数,拷贝构造函数,赋值函数全部私有化,外部无法创建对象。
    SObject& operator= (const SObject&);   
    SObject()  {  }
public:
    static SObject* GetInstance();   // 外部函数只有通过此函数得到唯一的一个类的对象。
{
    if(c_instance == NULL)
     {
       c_instance = new SObject(); // 在这里创建唯一一个对象
     }
return c_intance;
   } }; SObject* SObject::c_instance = NULL; int main() { SObject* s = SObject::GetInstance(); // 三个对象地址相同,说明其是一个对象 SObject* s1 = SObject::GetInstance(); SObject* s2 = SObject::GetInstance(); cout << "addr of s" << s << endl; // 0x7fffdcb61e70 cout << "addr of s1" << s1 << endl; // 0x7fffdcb61e70 cout << "addr of s2" << s2 << endl; // 0x7fffdcb61e70
// 并没有释放对象 ,存在于整个软件运行周期
return 0; }

进阶的单例类模板:

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

template
< typename T >
class Singleton
{
    static T* c_instance;
public:
    static T* GetInstance();
    {
        if( c_instance == NULL )
        {
            c_instance = new T();
        }  
        return c_instance;
    }
};

template
< typename T >
T* Singleton<T>::c_instance = NULL;

#endif
View Code
#include <iostream>
#include <string>
#include "Singleton.h"

using namespace std;

class SObject
{
    friend class Singleton<SObject>;    // Singleton是SObject的友元   自定义类SObject使用单例模式
    SObject(const SObject&);
    SObject& operator= (const SObject&);  
    SObject()  { }
public: 
};

int main()
{
    SObject* s = Singleton<SObject>::GetInstance();
    SObject* s1 = Singleton<SObject>::GetInstance();
    SObject* s2 = Singleton<SObject>::GetInstance();
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/zsy12138/p/10863213.html