[Design Pattern] 创建型模式 - 单例模式

38 阅读1分钟

单例模式是一种创建型设计模式, 让你能够保证一个类只有一个实例, 并提供一个访问该实例的全局节点。

#include <iostream>
#include <string>

using namespace std;

class Singleton {
private:
    static Singleton* instance;
    Singleton() {}  // 私有构造函数

public:
    Singleton(const Singleton&) = delete;            // 禁止拷贝构造
    Singleton& operator=(const Singleton&) = delete; // 禁止赋值操作

    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }
};

Singleton* Singleton::instance = nullptr;

int main(){
    Singleton* s1 = Singleton::getInstance();
    Singleton* s2 = Singleton::getInstance();
    cout << s1 << endl;
    cout << s2 << endl;
    return 0;
}