一、static 与单例模式
单例模式也就是简单的一种设计模式,它需要:
保证一个类只有一个实例,并提供一个全局访问点
禁止拷贝
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
#include <iostream>
using namespace std; class Singleton { public: static Singleton *GetInstance() { if (instance_ == NULL) { instance_ = new Singleton; } return instance_; } ~Singleton() { cout << "~Singleton ..." << endl; } private: Singleton( const Singleton &other); Singleton & operator=( const Singleton &other); Singleton() { cout << "Singleton ..." << endl; } static Singleton *instance_; }; Singleton *Singleton::instance_; int main( void) { //Singleton s1; //Singleton s2; Singleton *s1 = Singleton::GetInstance(); Singleton *s2 = Singleton::GetInstance(); //Singleton s3(*s1); // 调用拷贝构造函数 return 0; } |
上述程序虽然调用了两个GetInstance函数,但只调用一次构造函数,即创建一个对象。将赋值运算符和拷贝构造函数声明为私有,禁止拷贝。但程序存在一个问题就是对象生存期到时不会被析构。
为了解决对象不会被析构的问题,可以使用一个静态的嵌套类对象来解决:
C++ Code
1
2 3 4 5 6 7 8 9 1 |