C++单件模式

解决的问题

有一些对象其实我们只需要一个,比方说: 线程池、缓存、对话框、处理偏好设置和注册表的对象、日志对象,充当打印机、显卡等设备的驱动程序的对象。事实上,这类对象只能有一个实例,如果制造出多个实例,就会导致许多问题产生,例如:程序的行为异常、资源使用过量,或者不一致的结果。

意图

保证一个类仅有一个实例,并提供一个访问它的全局访问点。

适用性

  • 当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时。
  • 当这个唯一示例应该时通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。

示意性代码

#include <iostream>

class Singleton {

public: 
    static Singleton* Instance() {
        if (_instance == nullptr) {
            _instance = new Singleton();
        }

        return _instance;
    }

    ~Singleton() {
        delete _instance;
    }

private:
    Singleton() = default;
    Singleton(const Singleton &) = delete;
    Singleton(Singleton &&) = delete;
    Singleton& operator=(const Singleton &) = delete;
    Singleton& operator=(const Singleton &&) = delete;
 
public: 
    static Singleton* _instance;
};

Singleton* Singleton::_instance = nullptr;

int main() {
    Singleton* s1 = Singleton::Instance();
    Singleton* s2 = Singleton::Instance();

    if (s1 == s2) {
        std::cout << "Objects are the same" << std::endl;
    } else {
        std::cout << "Objects are not the same" << std::endl;
    }

    return 0;
}
posted @ 2022-07-26 09:44  岁月飞扬  阅读(30)  评论(0编辑  收藏  举报