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

来源:互联网 发布:淘宝怎样做充值话费 编辑:程序博客网 时间:2024/06/13 22:07

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

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

Singleton.h
#ifndef _SINGLETON_H_#define _SINGLETON_H_#include <iostream>using namespace std;#include <pthread.h>  static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;class Singleton{    public:        static Singleton *GetInstance(){            cout<<"to get Singleton instance"<<endl;            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"<<endl;        }        static Singleton *m_Instance ;        // This is important ---- Garbage Collector        class GC {            public:            GC(){                cout<<"GC construction"<<endl;            }            ~GC(){                cout<<"GC destruction"<<endl;                // We can destory all the resouce here                if (m_Instance != NULL){                    delete m_Instance;                    m_Instance = NULL;                    cout<<"Singleton destruction"<<endl;                }            }        };        // 定义一个静态成员,在程序结束时,系统会调用它的析构函数          static GC gc;  //垃圾回收类的静态成员        public :             void SayHello();};#endif
Singleton.cpp
#include <stdio.h>#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 <stdio.h>#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 <stdio.h>#include "Singleton.h"int printDemo(); // or put to a header fileint 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 constructionto get Singleton instanceSingleton constructionto get Singleton instance(printDemo:8)singletonObj=0x190a010###SayHello(10)###index=0(main:9)###SayHello(10)###index=1GC destructionSingleton destruction
原创粉丝点击