• c++设计模式之单例模式


    单例模式:
    目的:保证每个类只有一个静态对象
    实现方式:
    1.构造函数私有化
    2.公有静态类对象指针
    3.产生静态类对象指针的公有函数
    分类:
    懒汉式:在需要的时候才进行初始化
    优点:避免内存消耗
    缺点:需要加锁,影响执行效率
    饿汉式:一开始就进行初始化
    优点:不需要加锁,执行速度快
    缺点:会造成内存消耗

    注意:
    1.双检索机制--->懒汉式,在判断之前需要在加上一个锁
    2.资源//singleton.h

      1 #pragma once
      2 #include <mutex>
      3 
      4 
      5 class singleton
      6 {
      7 public:
      8     static singleton* singleton_;
      9     static singleton* getInstance();
     10     void doSomeThing();
     11 private:
     12     static std::mutex mutex_;
     13     singleton();
     14     ~singleton();
     15 };
     16 
     17 
     18 //singleton.cpp----此为懒汉式
     19 #include "pch.h"
     20 #include <iostream>
     21 #include "singleton.h"
     22 
     23 singleton *singleton::singleton_ = NULL;
     24 std::mutex singleton::mutex_;
     25 
     26 singleton::singleton()
     27 {
     28 }
     29 
     30 
     31 singleton::~singleton()
     32 {
     33     if (singleton_) 
     34     {
     35         delete singleton_;
     36         singleton_ = NULL;
     37     }
     38 }
     39 
     40 singleton* singleton::getInstance() 
     41 {
     42     if (singleton_==NULL)
     43     {
     44         std::lock_guard<std::mutex> lock(mutex_);
     45         if (singleton_==NULL)
     46         {
     47             singleton_ = new singleton();
     48         }
     49     }
     50     return singleton_;
     51 }
     52 
     53 void singleton::doSomeThing() 
     54 {
     55     std::cout << "do some thing!";
     56 }
     57 
     58 //singleton.cpp----此为恶汉式
     59 #include "pch.h"
     60 #include <iostream>
     61 #include "singleton.h"
     62 
     63 singleton *singleton::singleton_ =  new singleton();;
     64 std::mutex singleton::mutex_;
     65 
     66 singleton::singleton()
     67 {
     68 }
     69 
     70 
     71 singleton::~singleton()
     72 {
     73     if (singleton_) 
     74     {
     75         delete singleton_;
     76         singleton_ = NULL;
     77     }
     78 }
     79 
     80 singleton* singleton::getInstance() 
     81 {
     82     return singleton_;
     83 }
     84 
     85 void singleton::doSomeThing() 
     86 {
     87     std::cout << "do some thing!";
     88 }
     89 
     90 
     91 //测试代码
     92 #include "pch.h"
     93 #include <iostream>
     94 #include "singleton.h"
     95 
     96 int main()
     97 {
     98     singleton::getInstance()->doSomeThing();
     99     getchar();
    100 }

    运行结果:

    do some thing!

  • 相关阅读:
    GIT操作远程仓库
    GIT基本使用方式
    Docker网络及私有仓库配置
    Docker容器资源控制
    Docker基本使用方法
    [linux Tcmd] sh source
    hh
    推演论
    智能小车项目计划
    [CATARC_2017S] Week2
  • 原文地址:https://www.cnblogs.com/HPAHPA/p/10247273.html
Copyright © 2020-2023  润新知