-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFlyweight-Pattern.js
48 lines (42 loc) · 1.06 KB
/
Flyweight-Pattern.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// 享元模式(Flyweight Pattern)
// 构建享元对象
class Modal {
constructor (id, gender) {
this.gender = gender
this.name = `${gender}${id}`
}
}
// 构建享元工厂
class ModalFactory {
// 单例模式
static create (id, gender) {
if (this[gender]) {
return this[gender]
}
return this[gender] = new Modal(id, gender)
}
}
// 管理外部状态
class TakeClothersManager {
// 添加衣服款式
static addClothes (id, gender, clothes) {
const modal = ModalFactory.create(id, gender)
this[id] = {
clothes,
modal
}
}
// 拍照
static takePhoto (id) {
const obj = this[id]
console.log(`${obj.modal.gender}模${obj.modal.name}穿${obj.clothes}拍了照`)
}
}
for (let i = 0; i < 10; i++) {
TakeClothersManager.addClothes(i, '男', `服装${i}`)
TakeClothersManager.takePhoto(i)
}
for (let i = 10; i < 20; i++) {
TakeClothersManager.addClothes(i, '女', `服装${i}`)
TakeClothersManager.takePhoto(i)
}