单例模式 (Singleton)

1.基础
懒汉模式与饿汉模式

点击查看代码
#include<iostream>

using namespace std;

class Singleton{
private:
    Singleton() {};
public:
    void print() {
        cout << "i am singleton " << endl;
    }
    static Singleton* GetInstance() {
        // 懒汉模式
        if (nullptr == _onlyInstance) {
            _onlyInstance = new Singleton();
        }
        return _onlyInstance;
    }
    static void Destroy() {
        if (!_onlyInstance) {
            delete _onlyInstance;
        }
    }
private:
    static Singleton* _onlyInstance ;
};
// 懒汉模式
// Singleton* Singleton::_onlyInstance = nullptr;
// 饱汉模式
Singleton* Singleton::_onlyInstance = new Singleton();// 在类Singleton 作用域调用私有构造函数
// 需要 delete
int main() {
    Singleton::GetInstance()->print();
    // static Singleton* s = new Singleton();
    Singleton::Destroy();
    return 0;
}

**2.进阶**
posted @ 2022-06-19 19:16  locker_10086  阅读(11)  评论(0编辑  收藏  举报