单例模式是应用最多的一种设计模式,它要求每个类有且只能有一个实例对象,所以用C++设计一个单例模式的方法如下:
1 构造函数声明为私有; 这样就保证了不能随意构造一个对象
2 将拷贝构造函数与等号运算符声明为私有,并不提供他们的实现; 即禁止对象被拷贝。
3 在类中声明一个静态的全局访问接口;
4 声明一个静态的私有实例化指针;
- 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::GetInstance();
- Singleton *s2 = Singleton::GetInstance(); //s2的地址等于s1,即指向同一对象
- //Singleton s3(*s1); //既然是单例模式,是不允许被拷贝的。编译会出错
- return 0;
- }
第一种解决方式:
- class Singleton
- {
- ...
- //提供一个回收接口,在应用中显示调用回收资源
- static void Free()
- {
- delete instance_;
- }
- ....
- };
- int main()
- {
- ...
- Singleton::Free(); //要显示调用进行资源回收
- }
第二种解决方式:
- class Singleton
- {
- ...
- public:
- class Garbo //资源回收机制
- {
- public:
- ~Garbo()
- {
- if( Singleton::instance_ != NULL )
- {
- delete instance_;
- }
- }
- };
- ...
- private:
- ...
- static Garbo garbo_; //引用性声明
- };
- Singleton::Garbo Singleton::garbo_;//定义性声明
下面提供另一种实现C++单例类模式的方法:
- class Singleton
- {
- public:
- static Singleton& GetInstance()
- {
- static Singleton instance_; return instance_;
- }
- ~Singleton()
- {
- cout << "~Singleton"<<endl;
- }
- private:
- Singleton()
- {
- cout << "Singleton "<<endl;
- }
- Singleton(const Singleton &other);
- Singleton & operator=(const Singleton &other);
- };
- int main()
- {
- Singleton &s1 = Singleton::GetInstance();
- Singleton &s2 = Singleton::GetInstance(); //s1与s2是同一对象的引用
- return 0;
- }