C++中的单例类模板

2017-10-14  本文已影响0人  nethanhan

对于单例模式,我们都已经很熟悉了,这里我们来亲手制作一个单例类模板:

代码为下:

#include <iostream>
#include <string>

using namespace std;

class SObject
{
    //定一个指针
    static SObject* c_instance;
    SObject(const SObject&);
    SObject& operator= (const SObject&);
    
    SObject()
    {
    }
public:
    static SObject* GetInstance();
    
    void print()
    {
        cout << "this = " << this << endl;
    }
};

//初始化指针
SObject* SObject::c_instance = NULL;
//初始化的时候判断这个指针是否指空
SObject* SObject::GetInstance()
{
    if( c_instance == NULL )
    {
        c_instance = new SObject();
    }
    
    return c_instance;
}

int main()
{
    SObject* s = SObject::GetInstance();
    SObject* s1 = SObject::GetInstance();
    SObject* s2 = SObject::GetInstance();
    
    s->print();
    s1->print();
    s2->print();
    
    return 0;
}

运行结果为:

this = 0x7ff9a2c02680
this = 0x7ff9a2c02680
this = 0x7ff9a2c02680

虽然实现了需求,但是也存在了几个问题:

再来写一个示例:

Singleton.h类

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

template
< typename T >
class Singleton
{
    static T* c_instance;
public:
    static T* GetInstance();
};

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

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

#endif

调用类:

#include <iostream>
#include <string>
#include "Singleton.h"

using namespace std;

class SObject
{
    //使用友元
    friend class Singleton<SObject>;    // 当前类需要使用单例模式
    
    SObject(const SObject&);
    SObject& operator= (const SObject&);
    
    SObject()
    {
    }
public:
    
    void print()
    {
        cout << "this = " << this << endl;
    }
};

int main()
{
    SObject* s = Singleton<SObject>::GetInstance();
    SObject* s1 = Singleton<SObject>::GetInstance();
    SObject* s2 = Singleton<SObject>::GetInstance();
    
    s->print();
    s1->print();
    s2->print();
    
    return 0;
}

运行结果为:

this = 0x7fc241402680
this = 0x7fc241402680
this = 0x7fc241402680
上一篇 下一篇

猜你喜欢

热点阅读