Skip to content

Commit 5215433

Browse files
committed
单例模式
1 parent adb40f7 commit 5215433

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

Example/Factory-Method-Pattern.js

Lines changed: 0 additions & 1 deletion
This file was deleted.

Example/Singleton-Pattern.js

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,26 @@
1-
// 单例模式(Singleton Pattern)
1+
// 单例模式(Singleton Pattern)
2+
3+
// 惰性单例
4+
let lazySingle = (() => {
5+
let _instance = null
6+
// 单例
7+
Single = () => {
8+
let privateAttribute = '我是私有属性'
9+
privateMethod = () => {
10+
// 私有方法
11+
}
12+
return {
13+
publicMethod: () => {
14+
// 对外暴露方法
15+
},
16+
publicAttribute: '我是对外暴露属性'
17+
}
18+
}
19+
// 提供一个全局访问点
20+
return () => {
21+
if (!_instance) {
22+
_instance = Single()
23+
}
24+
return _instance
25+
}
26+
})()

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,11 @@
1414
目的:工厂模式是为了解耦,把对象的创建和使用的过程分开。
1515
场景:需要生成复杂对象,需要降低耦合度的场景。
1616

17-
> [工厂方法模式(Factory Method Pattern)](/Example/Factory-Method-Pattern.js)
18-
1917
> [单例模式(Singleton Pattern)](/Example/Singleton-Pattern.js)
18+
19+
定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
20+
目的:阻止其他对象实例化其自己的单例对象的副本,从而确保所有对象都访问唯一实例。
21+
场景:如一个系统中可以存在多个打印任务,但是同时只能有一个正在工作的任务。
2022

2123
> [建造者模式(Builder Pattern)](/Example/Builder-Pattern.js)
2224

0 commit comments

Comments
 (0)