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

在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 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值