单例模式的几种实现及其比较

来源:互联网 发布:大麦盒子怎么设置网络 编辑:程序博客网 时间:2024/05/21 09:17

1.惰性实现

class Singleton{    static Singleton singletonM;     int i;     Singleton(int x):i(x){}     Singleton& operator=(Singleton&);     Singleton(const Singleton&);public:     static Singleton& instance()
     {
         return singletonM;
     }
     int getValue(){ return i}
  
     void setValue(int x){ i=x ;}      
};
Singleton Singleton::s(48);
int main()
{
    static Singleton& s = Singleton::instance();
    cout<<s.getValue<<endl;
    static Singleton& s1. = Singleton::instance();
    s1.setValue(9);
    cout<<s.getValue()<<endl; 
}
创建单例模式关键是:
1.防止客户程序员获得任何控制其对象生存期的权利,因此必须将所有构造函数
声明为私有,并且防止编译器自动生成任何构造函数。
2.决定对象的创建方式。
这里是静态创建,称作惰性初始化。由于实例的创建不受客户程序员控制(在程序开始时初始化),所以
这种实现方式只有在对象创建代价不大,并且并不总是需要它的时候才有意义。


2.Meyers' singleton

class Singleton{     int i;     Singleton(int x):i(x){}     Singleton& operator=(Singleton&);     Singleton(const Singleton&);public:     static Singleton& instance()
     {  
          static Singleton s(47);
          return s;
     }
     int getValue(){ return i}
  
     void setValue(int x){ i=x ;}      
};
这种实现由Meyers最先提出(effective c++),故成为Meyers单例;实例在客户程序员调用 instance()时才会被

初始化。


3.template


4.线程安全

原创粉丝点击