C++实现单例模式的简单例程

在Java中使用单例模式是常用的事情
这里使用C++实现一次单例模式,虽然实际场景中很少使用

这次例程有四个文件
Singleton.h
Singleton.cpp
Demo.cpp
Client.cpp

Singleton.h
#ifndef _SINGLETON_H_
#define _SINGLETON_H_

#include 
using namespace std;

#include   

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

class Singleton{
    public:
        static Singleton *GetInstance(){
            cout<<"to get Singleton instance"<if (m_Instance == NULL){
                pthread_mutex_lock(&mutex); //lock();
                if (m_Instance == NULL){
                    m_Instance = new Singleton();
                }
                pthread_mutex_unlock(&mutex); //unlock();
            }
            return m_Instance;
        }

    private:
        Singleton(){
            cout<<"Singleton construction"<static Singleton *m_Instance ;

        // This is important ---- Garbage Collector
        class GC {

            public:
            GC(){
                cout<<"GC construction"<cout<<"GC destruction"<// We can destory all the resouce here
                if (m_Instance != NULL){
                    delete m_Instance;
                    m_Instance = NULL;
                    cout<<"Singleton destruction"<// 定义一个静态成员,在程序结束时,系统会调用它的析构函数  
        static GC gc;  //垃圾回收类的静态成员

        public : 
            void SayHello();
};

#endif
Singleton.cpp
#include 
#include "Singleton.h"

Singleton *Singleton::m_Instance = NULL;
Singleton::GC Singleton::gc;
//static int index;

void Singleton::SayHello(){
    static int index;
    printf("###%s(%d)###index=%d\n", __FUNCTION__, __LINE__,index++);
}
Demo.cpp
#include 
#include "Singleton.h"

int printDemo()
{
    //Singleton *singletonObj = Singleton::GetInstance();
    Singleton *singletonObj = Singleton::GetInstance();
    printf("(%s:%d)singletonObj=%p\n", __FUNCTION__, __LINE__, singletonObj);
    singletonObj->SayHello();
    return 0;
}
Client.cpp
#include 
#include "Singleton.h"

int printDemo(); // or put to a header file

int main(int argc, char *argv[]) {
    Singleton *singletonObj = Singleton::GetInstance();
    printDemo();
    printf("(%s:%d)\n", __FUNCTION__, __LINE__);
    singletonObj->SayHello();
    return 0;
}
运行结果
$ g++ Client.cpp Demo.cpp Singleton.cpp
$ ./a.out 
GC construction
to get Singleton instance
Singleton construction
to get Singleton instance
(printDemo:8)singletonObj=0x190a010
###SayHello(10)###index=0
(main:9)
###SayHello(10)###index=1
GC destruction
Singleton destruction

你可能感兴趣的:(Linux)