关于singleton模式的几种实现。

来源:互联网 发布:淘宝首页装修模板 编辑:程序博客网 时间:2024/05/16 12:08

这是我用的方法:

template<class T>
class TSingleton
{
public:
 //外部程序用来获取单一对象。
 static T* Instance(void)
 {
  if(m_instance.get() == NULL)
  {
   m_instance.reset(new T());
  }
  return m_instance.get();
 }
 template<class p>
 static T* Instance(p)
 {
  if(m_instance.get() == NULL)
  {
   m_instance.reset(new T(p));
  }
  return m_instance.get();
 }
 template<typename P1, typename P2>
 static T* Instance(P1 p1,P2 p2)
 {
  if(m_instance.get() == NULL)
  {
   m_instance.reset(new T(p1,p2));
  }
  return m_instance.get();
 }
protected:
 //外部程序不用使用构造函数。
 TSingleton(void){};
private:
 //屏蔽相关的缺省函数
 TSingleton(const TSingleton &);
 TSingleton& operator = (const TSingleton &);
private:
 //使用auto_ptr实现自动清理CSingleton对象
 static auto_ptr<T> m_instance;

};
template<class T>
auto_ptr<T> TSingleton<T>::m_instance = auto_ptr<T>(NULL);

 

class CSingletonEx : public TSingleton<CSingletonEx>
{
friend class TSingleton;
private:
 CSingletonEx(){m_a=10;};
 CSingletonEx(int a,int b)
 {
  m_a=a;m_b=b;
 }
public:
 int m_a;
 int m_b;
};

void main()
{
 CSingletonEx * s = CSingletonEx::Instance(3,4);
 cout<<s->m_a<<endl;
}

GOF中的方法:

TSingleton一样,但不用继承类:

class CSingletonEx :
{
friend class TSingleton;
private:
 CSingletonEx(){m_a=10;};
 CSingletonEx(int a,int b)
 {
  m_a=a;m_b=b;
 }
public:
 int m_a;
 int m_b;
};

void main()
{
 CSingletonEx *s = TSingleton<CSingletonEx>::Instance(3,4);
 cout<<s->m_a<<endl;
}

个人觉得第二中方法不好!!!

如果用继承,那么子类不用在重新屏蔽 拷贝构造函数,赋值函数等(因为这些会继承下来),

如果不用继承,那你将重写它们