单例模式
C#
单例模式:一个类只能有一个实例对象。这样就决定了它有以下几个特点。
- 不能被继承,那得用
sealed修饰类; - 将构造函数隐藏起来,
private构造函数; - 公有静态方法创建单一实例;
- 为了保证多线程情况下的单一实例原则,还得加个线程锁;
简单代码实现如下:
public sealed class Singletion
{
private static Singletion _singletion = null;
// 线程锁辅助对象
private static readonly object _lockObj = new object();
private Singletion()
{
}
public static Singletion GetInstance()
{
// 保证线程安全,多线程情况下只有一个对象实例
if (_singletion == null)
{
lock(_lockObj)
{
if (_singletion == null) {
_singletion = new Singletion();
}
}
}
return _singletion;
}
}
C++
#include <iostream>
#include "mutex"
/*成员变量静态*/
class SingletonLazy
{
private:
static SingletonLazy* m_instance;
SingletonLazy()
{
}
~SingletonLazy()
{
}
public:
static SingletonLazy* getInstance();
};
std::mutex g_mtx;
SingletonLazy* SingletonLazy::m_instance = NULL;
SingletonLazy* SingletonLazy::getInstance()
{
if (NULL == m_instance)
{
std::unique_lock<std::mutex> lock(g_mtx);
if (NULL == m_instance)
{
m_instance = new SingletonLazy;
}
}
return m_instance;
}
/*内部静态实例*/
class SingletonInside
{
private:
SingletonInside() {}
public:
static SingletonInside* getInstance()
{
/*
C++0X以后,要求编译器保证内部静态变量的线程安全性,可以不加锁。但C++ 0X以前,仍需要加锁。
*/
//Lock(); // not needed after C++0x
static SingletonInside instance;
//UnLock(); // not needed after C++0x
return &instance;
}
};
/*饿汉模式*/
class SingletonStatic
{
private:
static const SingletonStatic* m_instance;
SingletonStatic() {}
public:
static const SingletonStatic* getInstance()
{
return m_instance;
}
};
//外部初始化 before invoke main
const SingletonStatic* SingletonStatic::m_instance = new SingletonStatic;
int main()
{
SingletonLazy * obj1 = SingletonLazy::getInstance();
SingletonLazy * obj2 = SingletonLazy::getInstance();
if (obj1 == obj2) {
std::cout << "同一对象:" << obj1 << std::endl;
}
else {
std::cout << "1 2 不同一对象" << std::endl;
}
SingletonInside *obj11 = SingletonInside::getInstance();
SingletonInside *obj22 = SingletonInside::getInstance();
if (obj11 == obj22) {
std::cout << "同一对象:" << obj11 << std::endl;
}
else {
std::cout << "11 22 不同一对象" << std::endl;
}
const SingletonStatic* obj111 = SingletonStatic::getInstance();
const SingletonStatic* obj222 = SingletonStatic::getInstance();
if (obj111 == obj222) {
std::cout << "同一对象:" << obj111 << std::endl;
}
else {
std::cout << "111 222 不同一对象" << std::endl;
}
getchar();
return 0;
}
输出:
同一对象:009CAE20
同一对象:007CF316
同一对象:009CA758
参考:
浙公网安备 33010602011771号