From 8a876a756ef115936d401c3aecf7c2d83981dd22 Mon Sep 17 00:00:00 2001 From: XMuli Date: Sat, 24 Dec 2022 01:30:52 +0800 Subject: [PATCH] feat: add Singleton Pattern --- Studio/DesignPatterns/Singleton.cpp | 1 + Studio/DesignPatterns/Singleton.h | 23 ++++++++++++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/Studio/DesignPatterns/Singleton.cpp b/Studio/DesignPatterns/Singleton.cpp index 69acca0..dbb7fcd 100644 --- a/Studio/DesignPatterns/Singleton.cpp +++ b/Studio/DesignPatterns/Singleton.cpp @@ -1 +1,2 @@ #include "Singleton.h" + \ No newline at end of file diff --git a/Studio/DesignPatterns/Singleton.h b/Studio/DesignPatterns/Singleton.h index 11faed8..23c36ce 100644 --- a/Studio/DesignPatterns/Singleton.h +++ b/Studio/DesignPatterns/Singleton.h @@ -6,7 +6,7 @@ ******************************************************************/ #pragma once -// 《Effective C++》提出了一种更优雅的单例模式实现,称为 Meyers' Singleton +// 推荐使用 →《Effective C++》提出了一种更优雅的单例模式实现,称为 Meyers' Singleton class Singleton { public: @@ -22,3 +22,24 @@ private: Singleton& operator=(const Singleton& obj) = delete; }; +//--------------------------------------------------------- +// 不推荐使用 → Eager Singleton 是线程安全的,但存在潜在问题 no-local static 对象在不同编译单元中的初始化顺序是未定义的 +class Singleton2 +{ +public: + static Singleton2& instance() { + return instan; + } + +private: + Singleton2() {}; + ~Singleton2() {}; + Singleton2(const Singleton2&) = delete; + Singleton2& operator=(const Singleton2&) = delete; + +private: + static Singleton2 instan; +}; + +Singleton2 Singleton2::instan; +