添砖加瓦:设计模式(单例模式)

  1、单例定义及要素

  定义:

  保证一个类只有一个实例存在,同时提供能对该实例加以访问的全局访问方法(GoF中单例模式的定义)。

  要素:

  (1)某个类只能有一个实例

  (2)必须自行创建这个实例

  (3)必须自行向整个系统提供这个实例

  2、模式中的角色和职责

  Singleton(单例)在单例类的内部实现只生成一个实例,同时它提供一个静态的getInstance()工厂方法,让客户可以访问它的唯一实例;为了防止在外部对其实例化,将其构造函数设计为私有;在单例类内部定义了一个Singleton类型的静态对象,作为外部共享的唯一实例。

  使用步骤:

  (1)构造函数私有化

  (2)提供一个全局的静态方法来获取单例对象

  (3) 在类中定义一个静态指针,只想本类的变量

  3、单例模式的优缺点

优点
(1) 单例模式提供了对唯一实例的受控访问。
(2) 节约系统资源。 由于在系统内存中只存在一个对象。
缺点
(1) 扩展略难。 单例模式中没有抽象层。
(2) 单例类的职责过重。

  4、适用场景

(1) 系统只需要一个实例对象,如系统要求提供一个唯一的序列号生成器或资源管理器,或者需要考虑资源消耗太大而只允许创建一个对象。

(2) 客户调用类的单个实例只允许使用一个公共访问点,除了该公共访问点,不能通过其他途径访问该实例。 

5、实例

 

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 /*
 6     懒汉模式:在调用全局静态方法获取单例时,再进行创建。该模式下单例的创建是在程序运行中进行
 7 */
 8 class Singleton
 9 {
10 public:
11     //对外提供一个全局的静态方法
12     static Singleton *getInstance()
13     {
14         if (instance == NULL)
15             instance = new Singleton;
16         m_count++;
17         return instance;
18     }
19 
20     int getCount()
21     {
22         return m_count;
23     }
24 
25 private:
26     //私有化构造函数
27     Singleton()
28     {
29         instance = NULL;
30         m_count = 0;
31         cout << "Singleton() running" << endl;
32     }
33     //在类中定义一个静态指针,指向本类的变量
34     static Singleton *instance;
35     static int m_count;
36 };
37 //静态变量的初始化要放在全局位置上
38 Singleton *Singleton::instance = NULL;
39 int Singleton::m_count = 0;
40 
41 
42 /*
43     饿汉模式:实例的创建是在声明的时候创建的,即在编译的时候就已创建
44 */
45 class Singleton2
46 {
47 public:
48     static    Singleton2*    getInstance() {
49         m_count++;
50         return    instance;
51     }
52     int    getCount() {
53         return    m_count;
54     }
55 private:
56     Singleton2() {
57         instance = NULL;
58         m_count = 0;
59     }
60     static    Singleton2    *    instance;
61     static int    m_count;
62 };
63 
64 Singleton2 *Singleton2::instance = new Singleton2;
65 int Singleton2::m_count = 0;
66 
67 int main(int argc, char* argv[])
68 {
69     cout << "----------        以下 是 懒汉式    ------------" << endl;
70     Singleton *single = Singleton::getInstance();
71     cout << single->getCount() << endl;
72     Singleton *single2 = Singleton::getInstance();
73     cout << single2->getCount() << endl;
74 
75     if (single == single2)
76         cout << "相同" << endl;
77     else
78         cout << "不同" << endl;
79 
80     cout << "----------        以下 是 饿汉式    ------------" << endl;
81     Singleton2    *    singer3 = Singleton2::getInstance();
82     cout << singer3->getCount() << endl;
83     Singleton2    *    singer4 = Singleton2::getInstance();
84     cout << singer4->getCount() << endl;
85     if (singer3 == singer4)
86         cout << "相同" << endl;
87     else
88         cout << "不同" << endl;
89 
90     getchar();
91     return 0;
92 }
View Code

 

 

 

原文地址:https://www.cnblogs.com/lianshuiwuyi/p/7762794.html