Skip to content

Commit 0faedce

Browse files
committed
feat: add singleton-pattern
1 parent c7f30b2 commit 0faedce

File tree

5 files changed

+766
-705
lines changed

5 files changed

+766
-705
lines changed

plans.svg

Lines changed: 713 additions & 705 deletions
Loading

plans.xmind

30.5 KB
Binary file not shown.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
### 单例模式
2+
3+
单例模式(`Singleton Pattern`)是最简单的设计模式之一。这种类型的设计模式属于创建型模式, 它提供了一种创建对象的最佳方式。
4+
5+
这种模式涉及到一个单一的类, 该类负责创建自己的对象, 同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式, 可以直接访问, 不需要实例化该类的对象。
6+
7+
- 单例类只能有一个实例。
8+
9+
- 单例类必须自己创建自己的唯一实例。
10+
11+
- 单例类必须给所有其他对象提供这一实例。
12+
13+
### UML类图
14+
15+
##### 传统的 Java 类图
16+
17+
![singleton-pattern.png](./images/singleton-pattern.png)
194 KB
Loading
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
* @Author: Rainy
3+
* @Date: 2019-11-14 19:25:01
4+
* @LastEditors: Rainy
5+
* @LastEditTime: 2019-12-09 19:49:36
6+
*/
7+
8+
class SingleObject {
9+
showMessage(): string {
10+
return '';
11+
}
12+
}
13+
14+
// @ts-ignore
15+
SingleObject.getInstance = (() => {
16+
let _instance = null;
17+
if (_instance === null) {
18+
_instance = new SingleObject();
19+
}
20+
return _instance;
21+
})();
22+
23+
class Singleton {
24+
private _instance: SingleObject | null;
25+
26+
constructor() {
27+
this._instance = null;
28+
}
29+
30+
getInstance(): SingleObject {
31+
if (!this._instance) {
32+
this._instance = new SingleObject();
33+
}
34+
return this._instance;
35+
}
36+
}

0 commit comments

Comments
 (0)