首页 > 编程语言 > 详细

设计模式入门,单件模式,c++代码实现

时间:2017-07-03 15:40:46      阅读:228      评论:0      收藏:0      [点我收藏+]

// test05.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
//设计模式第5章 单件模式

class Singleton
{
private:
    static Singleton* uniqueInstance;

private:
    Singleton(){}

public:
    static synchronized Singleton* getInstance()//synchronized在java中表示线程同步,多线程保护
    {
        if (uniqueInstance == NULL)
        {
            uniqueInstance = new Singleton();
        }

        return uniqueInstance;
    }
};

class Singleton1
{
private:
    static Singleton1* uniqueInstance = new Singleton1();

private:
    Singleton1(){}

public:
    static Singleton1* getInstance()
    {
        return uniqueInstance;
    }

};

class Singleton2
{
private:
    volatile static Singleton2* uniqueInstance;

private:
    Singleton2(){}

public:
    volatile static Singleton2* getInstance()
    {
        if (uniqueInstance == NULL)
        {
            synchronized(Singleton2.class)//java中的锁
            {
                if (uniqueInstance == NULL)
                {
                    uniqueInstance = new Singleton2();
                }
            }
        }
        return uniqueInstance;
    }
};
int _tmain(int argc, _TCHAR* argv[])
{
    return 0;
}


设计模式入门,单件模式,c++代码实现

原文:http://www.cnblogs.com/wangting235/p/7111044.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!