feat: Singleton.
Implemented a demo for the Singleton.
This commit is contained in:
parent
5f6a05c86a
commit
f7eac92f68
24
05_singleton.cpp
Normal file
24
05_singleton.cpp
Normal file
@ -0,0 +1,24 @@
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class Singleton {
|
||||
Singleton() {}
|
||||
public:
|
||||
// Copy construction and assignment is disabled;
|
||||
Singleton(Singleton &other) = delete;
|
||||
void operator=(const Singleton &) = delete;
|
||||
|
||||
static Singleton& get_instance() {
|
||||
static Singleton s;
|
||||
return s;
|
||||
}
|
||||
|
||||
void f() {
|
||||
cout << "Singleton::f()" << endl;
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
Singleton::get_instance().f();
|
||||
}
|
||||
8
notes.md
8
notes.md
@ -25,3 +25,11 @@
|
||||
解决方案是有一种生成器类专门负责构建复杂对象。对于每一种参数,生成器类定义了接受各个参数的函数,从而做到分步创建对象。参数输入结束后,生成器类可以基于之前输入的参数创建这一复杂对象。
|
||||
|
||||
对于复杂场景,比如生成器需要输入十种参数,可以添加一个指导者封装这些输入这几种参数的过程。它提供了一种简化的构建流程,客户端不需要关心构建细节,代价是牺牲了一定的灵活性,因为客户无法定制每一步。
|
||||
|
||||
## 单例模式(Singleton)
|
||||
|
||||
有些时候,我们希望一个类只被实例化一次,且能在全局被访问,比如一个事件模拟器。朴素的想法是直接用一个全局变量。但这使得模块间强耦合,这些模块依赖隐式的、看不见的全局状态。且多个全局变量出现时依赖难以管理。
|
||||
|
||||
单例模式是一种解决方案,这个类只通过静态的 `get_instance()` 提供统一访问方式,并且不提供拷贝构造和赋值操作。这样多个依赖的全局变量可以在这个类里管理。此外测试时可以只改内部实现,对外接口不变,提高了可维护性与可测试性。
|
||||
|
||||
具体实现上有一些技巧。为了只创建一次,可以用 `get_instance()` 中使用 `static` 变量(懒汉式),也可以这个类有一个 `static` 类成员(饿汉式),还可以用 `static` 指针成员,对于指针为空时(第一次访问)额外做初始化(需要注意创建时的线程安全,比如双检查)。
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user