1.单例模式

需求的提出
在架构设计时,某些类在整个生命周期中最多只能有一个对象存在(single instance)

如何定义一个类,使得这个类最多只能创建一个对象?

要控制类的对象数目,必须对外隐藏构造函数
思路:
—-将构造函数的访问属性设置为private
—-定义instance并初始化为NULL
—-当需要使用对象时,访问instance的值
空值:创建对象,并用instance标记
非空值:返回instance标记的对象

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. class SObject
  5. {
  6. static SObject* c_instance; //声明,因为是static的,所以要到类的外面进行定义
  7. SObject()
  8. {
  9. }
  10. SObject(const SObject&); //私有化拷贝构造
  11. SObject& operator =(const SObject&); //私有化赋值重载
  12. public:
  13. static SObject* GetInstance();
  14. void print()
  15. {
  16. cout << "this = " << this << endl;
  17. }
  18. };
  19. SObject* SObject::c_instance = NULL;
  20. SObject* SObject::GetInstance()
  21. {
  22. if (c_instance == NULL)
  23. {
  24. c_instance = new SObject();
  25. }
  26. return c_instance;
  27. }
  28. int main()
  29. {
  30. SObject* s1 = SObject::GetInstance();
  31. SObject* s2 = SObject::GetInstance();
  32. s1->print();
  33. s2->print();
  34. return 0;
  35. }

2.单例类的实现

存在的问题:
—-需要使用单例模式时:
必须定义静态变量c_instance
必须定义静态成员函数GetInstance()
解决方案:将单例模式相关的代码抽取出来,开发单例类模板。当需要单例类时,直接使用单例类模板。

  1. #ifndef _SINGLETON_H_
  2. #define _SINGLETON_H_
  3. template
  4. < typename T >
  5. class Singleton
  6. {
  7. static T* c_instance;
  8. public:
  9. static T* GetInstance();
  10. };
  11. template
  12. < typename T >
  13. T* Singleton<T>::c_instance = NULL;
  14. template
  15. < typename T >
  16. T* Singleton<T>::GetInstance()
  17. {
  18. if( c_instance == NULL )
  19. {
  20. c_instance = new T();
  21. }
  22. return c_instance;
  23. }
  24. #endif
  25. #include <iostream>
  26. #include <string>
  27. #include "Singleton.h"
  28. using namespace std;
  29. class SObject
  30. {
  31. friend class Singleton<SObject>; // 声明当前类需要使用单例模式
  32. SObject(const SObject&);
  33. SObject& operator= (const SObject&);
  34. SObject()
  35. {
  36. }
  37. public:
  38. void print()
  39. {
  40. cout << "this = " << this << endl;
  41. }
  42. };
  43. int main()
  44. {
  45. SObject* s = Singleton<SObject>::GetInstance();
  46. SObject* s1 = Singleton<SObject>::GetInstance();
  47. SObject* s2 = Singleton<SObject>::GetInstance();
  48. s->print();
  49. s1->print();
  50. s2->print();
  51. return 0;
  52. }

小结

1.单例模式时开发中最常用的设计模式之一
2.单例模式的应用使得一个类最多只有一个对象
3.可以将单例模式相关的代码抽象成类模板
4.需要使用单例模式的类直接使用单例模板