实例编程 C++ c# 分别实现单件模式

豆豆网   技术应用频道   2008年04月29日    社区交流

本文详细介绍实例编程 C++ 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(new Singleton());
}
return pInstance.get();
}
protected:
Singleton(){}
private:
static std::auto_ptr pInstance;
};
3) 线程安全

来源:博客网    责编:豆豆技术应用

正在加载评论...