首页 > 编程语言 >设计模式<c++> (2)单例模式

设计模式<c++> (2)单例模式

时间:2023-12-24 19:44:42浏览次数:30  
标签:std Singleton const string value static 模式 单例 设计模式

#include <iostream>
#include <thread>
#include <mutex>

class Singleton
{
private:
    static Singleton* pinstance_;
    static std::mutex mutex_;

protected:
    Singleton(const std::string value) : value_(value)
    {
    }
    ~Singleton() {}
    std::string value_;

public:
    /**
     * Singletons should not be cloneable.
     */
    Singleton(Singleton& other) = delete;
    /**
     * Singletons should not be assignable.
     */
    void operator=(const Singleton&) = delete;
    /**
     * This is the static method that controls the access to the singleton
     * instance. On the first run, it creates a singleton object and places it
     * into the static field. On subsequent runs, it returns the client existing
     * object stored in the static field.
     */

    static Singleton* GetInstance(const std::string& value);
    /**
     * Finally, any singleton should define some business logic, which can be
     * executed on its instance.
     */
    void SomeBusinessLogic()
    {
        // ...
    }

    std::string value() const {
        return value_;
    }
};




/**
 * Static methods should be defined outside the class.
 */

Singleton* Singleton::pinstance_{ nullptr };
std::mutex Singleton::mutex_;

/**
 * The first time we call GetInstance we will lock the storage location
 *      and then we make sure again that the variable is null and then we
 *      set the value. RU:
 */
Singleton* Singleton::GetInstance(const std::string& value)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (pinstance_ == nullptr)
    {
        pinstance_ = new Singleton(value);
    }
    return pinstance_;
}

void ThreadFoo() {
    // Following code emulates slow initialization.
    //std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    Singleton* singleton = Singleton::GetInstance("FOO");
    std::cout << singleton->value() << "\n";
}

void ThreadBar() {
    // Following code emulates slow initialization.
    //std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    Singleton* singleton = Singleton::GetInstance("BAR");
    std::cout << singleton->value() << "\n";
}

int main()
{
    std::cout << "If you see the same value, then singleton was reused (yay!\n" <<
        "If you see different values, then 2 singletons were created (booo!!)\n\n" <<
        "RESULT:\n";
    std::thread t1(ThreadFoo);
    std::thread t2(ThreadBar);
    t1.join();
    t2.join();

    return 0;
}

单例模式如果不加互斥锁,则是线程不安全的(多个线程会出现多个实例的情况);

参考C++ 单例模式讲解和代码示例 (refactoringguru.cn)

标签:std,Singleton,const,string,value,static,模式,单例,设计模式
From: https://www.cnblogs.com/airduce/p/17924764.html

相关文章

  • 观察者模式揭秘:实现松耦合的事件通知机制
    推荐语本篇文章深度剖析了观察者模式的核心原理及其在软件开发中的重要应用,通过清晰而深入的讲解,读者小伙伴可以深入理解观察者模式如何实现松耦合的事件通知机制,从而构建更灵活、可扩展的软件系统。本文既适合希望深入了解设计模式的专业人士,也适合希望提升代码质量和可维护性的开......
  • Java涉及模式有几种,以及什么时候使用
    Java涉及的设计模式一共有23种,按照功能分为三类:创建型模式:包括工厂模式、抽象工厂模式、单例模式、建造者模式和原型模式。当需要对对象的创建进行更好的抽象和封装时,可以考虑使用创建型模式。比如,当系统中的对象创建过程较为复杂,希望封装这些复杂的创建过程,或者需要对对象的创......
  • 提高代码复用性与可维护性:深入剖析模板方法模式
    什么是模板方法模式模板方法模式是一种行为型设计模式,它定义了一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定步骤。在模板方法模式中,抽象类负责给出算法的轮廓和骨架(由一个或多个模板方法组成),而实现类......
  • 策略模式(Strategy Pattern) .Net Core实现
    在策略模式(StrategyPattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的context对象。策略对象改变context对象的执行算法。意图:定义一系列的算法,把它们一个个......
  • 设计模式<c++> (1)策略模式
    一、定义策略模式定义了算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户。二、使用场景客户需要很多种鸭子。要求:1.每种鸭子都要会游泳。2.每种鸭子有叫和飞的行为。3.鸭子的叫和飞的行为可以在使用......
  • 设计模式之单例模式
    单例模式(单例模式)定义==单例模式==确保一个类只有一个实例,并提供一个全局访问点。单例模式实现的方式1.饿汉式publicclassHungry{//构造器私有privateHungry(){}//类加载时就初始化,主动创建privatestaticHungryhungry=newHungry();......
  • 设计模式—工厂模式
    介绍代码接口创建Shape接口publicinterfaceShape{voiddraw();}实现类创建Shape接口的三个实现类:Cirle、Rectangle、SquarepublicclassCircleimplementsShape{@Overridepublicvoiddraw(){System.out.println("Circle");}}......
  • 26.基于 page object 模式的测试框架优化实战
    目录异常处理(弹窗黑名单)日志记录报告生成测试数据的数据驱动异常弹框处理定义黑名单列表处理弹框#声明一个黑名单defblack_wrapper(fun):defrun(*args,**kwargs):basepage=args[0]try:returnfun(*args,**kwargs)......
  • 设计模式—适配器模式
    介绍代码接口定义媒体播放器接口MediaPlayer,其中play方法用于播放媒体文件publicinterfaceMediaPlayer{publicvoidplay(StringaudioType,StringfileName);}定义高级播放器接口AdvancedMediaPlayer,规定指定类型媒体的播放方法publicinterfaceAdvancedMe......
  • 一文看懂java单例模式
    ​ Java单例模式是一种常用的创建型设计模式,用于确保一个类只有一个实例,并提供一个全局访问点来访问该实例。在Java中,有多种方式可以实现单例模式,下面详细介绍其中的几种常见实现方式。1什么是创建型设计模式?处理对象创建的模式,简答的理解就是如何创建对象?很多人都会想到new......