实例编程 C++ c# 分别实现单件模式
1)
public sealed class Singleton
{
static Singleton instance = null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
2) 线程安全
public sealed class Singleton
{
static Singleton instance = null;
static readonly object lockObj = new object();
private Singleton()
{
}
public static Singleton Instance
{
get
{
lock (lockObj)
{
if (instance == null)
{
instance = new Singleton();
}
}
return instance;
}
}
}
C++:
1)
class Singleton
{
public:
static Singleton * Instance()
{
if( 0== _instance)
{
_instance = new Singleton;
}
return _instance;
}
protected:
Singleton(){}
virtual ~Singleton(void){}
static Singleton* _instance;
};
2) 利用智能指针进行垃圾回收
class Singleton
{
public:
~Singleton(){}
static Singleton* Instance()
{
if(!pInstance.get())
{
pInstance = std::auto_ptr
}
return pInstance.get();
}
protected:
Singleton(){}
private:
static std::auto_ptr
};
3) 线程安全