• 单例模式


    一、概念

    单例模式是一种常用的软件设计模式。它的核心结构只包含一个被称为单例的特殊类。它的目的是保证一个类仅有一个实例,并提供一个访问它的全局访问点,该实例被所有程序模块共享

    二、类型

    懒汉式、饿汉式和双重锁的形式。

    懒汉:第一次用到类的实例的时候才回去实例化。
    饿汉:单例类定义的时候就进行实例化。

    三、代码

    #include <iostream>
    #include <mutex>
    #include <thread>
     
    using namespace std;
    mutex mu;//线程互斥对象

    /*饿汉*/ class Singleton_Hungry { private: Singleton_Hungry() { cout << "我是饿汉式,在程序加载时,我就已经存在了。" << endl; } static Singleton_Hungry* singleton; public: static Singleton_Hungry* getInstace() { return singleton; } }; //静态属性类外初始化 Singleton_Hungry* Singleton_Hungry::singleton = new Singleton_Hungry;
    /*懒汉*/
    class Singleton_Lazy { private: Singleton_Lazy() { cout << "我是懒汉式,在别人需要我的时候,我才现身。" << endl; } static Singleton_Lazy* singleton; public: static Singleton_Lazy* getInstance() { if (NULL == singleton) { mu.lock();//关闭锁 if (NULL == singleton) { singleton = new Singleton_Lazy; } mu.unlock();//打开锁 } return singleton; } }; Singleton_Lazy* Singleton_Lazy::singleton = NULL;
  • 相关阅读:
    LNMP 部署
    zabbix3.2安装graphtree3.0.4
    升级java8---from centos
    mysql5.6-5.7性能调优
    samba server install
    centos7 zabbix3 install done
    实验四总结
    第五周学习小结
    个人的一些html、css笔记
    为什么wait,notify,notifyAll定义在Object中?
  • 原文地址:https://www.cnblogs.com/judes/p/9359919.html
Copyright © 2020-2023  润新知