首页 > 代码库 > 设计模式入门,单件模式,c++代码实现
设计模式入门,单件模式,c++代码实现
// 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++代码实现