美文网首页
17.C++设计模式-单例

17.C++设计模式-单例

作者: 任振铭 | 来源:发表于2019-09-20 08:34 被阅读0次
#include <iostream>
using namespace std;
#include <mutex>
/*
    懒汉式
*/
class SingleTon {
private:
    SingleTon() {
        
    }
private:
    static SingleTon* ton;
    static int count;
    static mutex mu;
public:
    static SingleTon* getInstance() {
        if (ton == NULL) {
            mu.lock();
            if (ton == NULL)
            {
                ton = new SingleTon;
            }
            mu.unlock();
        }
        return ton;
    }

    void add() {
        count++;
        cout<<count<<endl;
    }


};
//静态变量的初始化放在类的外部
//?因为类定义的时候并没有分配内存,静态变量也不能等到创建对象的时候才分配内存,必须提前分配
SingleTon* SingleTon::ton = NULL;
int SingleTon::count = 1;
mutex SingleTon::mu;


/////////////////////////////////////////////////////////////////////////////////

/*
    饿汉式
*/
class SingleTon2 {
private:
    SingleTon2() {
    }
private:
    static SingleTon2* ton;
    static int count;
public:
    static SingleTon2* getInstance() {
        return ton;
    }

    void add() {
        count++;
        cout << count << endl;
    }


};
//静态变量的初始化放在类的外部
//?因为类定义的时候并没有分配内存,静态变量也不能等到创建对象的时候才分配内存,必须提前分配
SingleTon2* SingleTon2::ton = new SingleTon2;
int SingleTon2::count = 1;

void main() {

    SingleTon* s = SingleTon::getInstance();
    s->add();
    SingleTon* s1 = SingleTon::getInstance();
    s1->add();


    SingleTon2* s3 = SingleTon2::getInstance();
    s3->add();
    SingleTon2* s4 = SingleTon2::getInstance();
    s4->add();

    system("pause");
}

相关文章

  • 17.C++设计模式-单例

  • 单例模式Java篇

    单例设计模式- 饿汉式 单例设计模式 - 懒汉式 单例设计模式 - 懒汉式 - 多线程并发 单例设计模式 - 懒汉...

  • python中OOP的单例

    目录 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 单例

    目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • python 单例

    仅用学习参考 目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计...

  • 2018-04-08php实战设计模式

    一、单例模式 单例模式是最经典的设计模式之一,到底什么是单例?单例模式适用场景是什么?单例模式如何设计?php中单...

  • 设计模式第二篇、单例设计模式

    目录1、什么是单例设计模式2、单例设计模式的简单实现3、单例设计模式面临的两个问题及其完整实现4、单例设计模式的应...

  • 设计模式 - 单例模式

    设计模式 - 单例模式 什么是单例模式 单例模式属于创建型模式,是设计模式中比较简单的模式。在单例模式中,单一的类...

  • 2、创建型设计模式-单例设计模式

    江湖传言里的设计模式-单例设计模式 简介:什么是单例设计模式和应用 备注:面试重点考查 单例设计模式:这个是最简单...

  • 设计模式之单例模式

    单例设计模式全解析 在学习设计模式时,单例设计模式应该是学习的第一个设计模式,单例设计模式也是“公认”最简单的设计...

网友评论

      本文标题:17.C++设计模式-单例

      本文链接:https://www.haomeiwen.com/subject/ssvductx.html