zoukankan      html  css  js  c++  java
  • 6 创建型模式-----单例模式

    模式动机:对于系统中的某些类而言,确保只有一个实例运行很重要,例如一个系统只能有一个计时器或者ID生成器。

    模式定义(Singleton Pattern)确保一个类只有一个实例,并且该类自己负责创建它自己的唯一实例,而且还必须可以向系统提供这个实例。

    模式结构图:

     

    模式分析:单例类拥有一个私有构造函数,确保用户无法通过new关键字创建它;模式中包括一个静态工厂方法和一个静态(确保唯一性)私有变量,该静态方法:

            1> 负责实例化自己,然后存储到静态变量中;

            2> 提供系统可访问的接口。

     

    模式代码:

    bt_单例模式.h

     1 #ifndef SP_H
     2 #define SP_H
     3 
     4 #include <iostream>
     5 
     6 using namespace std;
     7 
     8 /*
     9     单例类
    10 */
    11 class Singleton
    12 {
    13 public:
    14     static Singleton* getInstance()     // public提供外部访问接口
    15     {
    16         if(instance == NULL)            // 检查是否之前已经实例化了
    17         {
    18             instance = new Singleton;
    19         }
    20         return instance;
    21     }
    22 
    23 private:
    24     Singleton(){ }                      // private构造确保客户不能new
    25   
    26 private:
    27     static Singleton* instance;         // static确保唯一性
    28 };
    29 Singleton* Singleton::instance = NULL;
    30 
    31 #endif // SP_H

    bt_原型模式.cpp

     1 #include "bt_单例模式.h"
     2 
     3 int main()
     4 {
     5     Singleton* instance1 = Singleton::getInstance();
     6     Singleton* instance2 = Singleton::getInstance();
     7 
     8     cout << "instance1 == instance2 : " << (instance1 == instance2 ? true : false) << endl;
     9 
    10     delete instance1;
    11 
    12     return 0;
    13 }
    
    

     

    模式优缺点:提供给系统一个唯一的实例,内存中永远只有一个对象,节约空间资源。同时也可以设计实例数目可控的单例扩展模式。缺点是单例类既是工厂又是产品,违背了“单一职责原则”。

     

     

  • 相关阅读:
    config Doku wiki
    [转载]【python】ipython与python的区别
    数组和指针
    C++初始化数据成员
    RSA算法原理
    C++四种cast
    百度笔试准备2
    百度笔试准备1
    百度面试准备
    C++的空类中默认产生哪些类成员函数
  • 原文地址:https://www.cnblogs.com/benxintuzi/p/4538952.html
Copyright © 2011-2022 走看看