作用:
1 保证类只实例化一次
2 提供全局访问接口
java实现
/**
* 单例模式
*/
public class Singleton {
private static Singleton singleton = null;//
private Singleton()
{
}
public static Singleton getInstance()
{
if(singleton==null)singleton = new Singleton();
return singleton;
}
public static void main(String[] args) {
Singleton s = Singleton.getInstance();
}
}
c++实现
Singleton.h
#pragma once
class Singleton
{
private:
static Singleton* singleton;
private:
Singleton(void);
public:
static Singleton* getInstance();
};
Singleton.cpp
#include "StdAfx.h"
#include "Singleton.h"
Singleton* Singleton:: singleton=0;
Singleton::Singleton(void)
{
}
Singleton* Singleton::getInstance()
{
if(singleton==0) singleton = new Singleton();
return singleton;
}
更多复杂用法,涉及并发访问及同步效率问题
http://www.iteye.com/topic/575052
单例模式的7种写法(基本都与线程安全相关)
http://cantellow.iteye.com/blog/838473
c++单例的几种写法,涉及自动析构和线程安全