- 懒汉方式。指全局的单例实例在第一次被使用时构建。
- 饿汉方式。指全局的单例实例在类装载时构建。
在Java编程语言中,单例模式(饿汉模式)应用的例子如下述代码所示:
public class Singleton {
private final static Singleton INSTANCE = new Singleton();
// Private constructor suppresses
private Singleton() {}
// default public constructor
public static Singleton getInstance() {
return INSTANCE;
}
}
在Java编程语言中,单例模式(懒汉模式)应用的例子如下述代码所示 (此种方法只能用在JDK5及以后版本(注意 INSTANCE 被声明为 volatie),之前的版本使用“双重检查锁”会发生非预期行为[1]):
public class Singleton {
private static volatile Singleton INSTANCE = null;
// Private constructor suppresses
// default public constructor
private Singleton() {}
//thread safe and performance promote
public static Singleton getInstance() {
if(INSTANCE == null){
synchronized(Singleton.class){
//when more than two threads run into the first null check same time, to avoid instanced more than one time, it needs to be checked again.
if(INSTANCE == null){
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
在C++编程语言中,单例模式应用的例子如下述代码所示(这里仅仅提供一个示例,这个例子对多线程的情况并不是安全的):
// ...
class lock
{
public:
lock();
lock(lock const & l);
~lock();
lock & operator =(lock const & l);
void request();
void release();
// ...
};
lock::lock()
{
// ...
}
// ...
lock::~lock()
{
// ...
}
// ...
void lock::request()
{
// ...
}
void lock::release()
{
// ...
}
// ...
// assumes _DATA_TYPE_ has a default constructor
template<typename _DATA_TYPE_>
class singleton
{
public:
static _DATA_TYPE_ * request();
static void release();
private:
singleton();
singleton(singleton<_DATA_TYPE_> const & s);
~singleton();
singleton<_DATA_TYPE_> & operator =(singleton<_DATA_TYPE_> const & s);
static _DATA_TYPE_ * pointer;
static lock mutex;
// ...
};
template<typename _DATA_TYPE_>
_DATA_TYPE_ * singleton<_DATA_TYPE_>::pointer = 0;
template<typename _DATA_TYPE_>
lock singleton<_DATA_TYPE_>::mutex;
template<typename _DATA_TYPE_>
_DATA_TYPE_ * singleton<_DATA_TYPE_>::request()
{
if(singleton<_DATA_TYPE_>::pointer == 0)
{
singleton<_DATA_TYPE_>::mutex.request();
if(singleton<_DATA_TYPE_>::pointer == 0)
{
singleton<_DATA_TYPE_>::pointer = new _DATA_TYPE_;
}
singleton<_DATA_TYPE_>::mutex.release();
}
return singleton<_DATA_TYPE_>::pointer;
}
template<typename _DATA_TYPE_>
void singleton<_DATA_TYPE_>::release()
{
if(singleton<_DATA_TYPE_>::pointer != 0)
{
singleton<_DATA_TYPE_>::mutex.request();
if(singleton<_DATA_TYPE_>::pointer != 0)
{
delete singleton<_DATA_TYPE_>::pointer;
singleton<_DATA_TYPE_>::pointer = 0;
}
singleton<_DATA_TYPE_>::mutex.release();
}
}
template<typename _DATA_TYPE_>
singleton<_DATA_TYPE_>::singleton()
{
// ...
}
// ...
int main()
{
int * s;
s = singleton<int>::request();
// ...
singleton<int>::release();
return 0;
}