File tree Expand file tree Collapse file tree 2 files changed +52
-1
lines changed Expand file tree Collapse file tree 2 files changed +52
-1
lines changed Original file line number Diff line number Diff line change 1- // 享元模式(Flyweight Pattern)
1+ // 享元模式(Flyweight Pattern)
2+
3+ // 构建享元对象
4+ class Modal {
5+ constructor ( id , gender ) {
6+ this . gender = gender
7+ this . name = `${ gender } ${ id } `
8+ }
9+ }
10+
11+ // 构建享元工厂
12+ class ModalFactory {
13+ // 单例模式
14+ static create ( id , gender ) {
15+ if ( this [ gender ] ) {
16+ return this [ gender ]
17+ }
18+ return this [ gender ] = new Modal ( id , gender )
19+ }
20+ }
21+
22+ // 管理外部状态
23+ class TakeClothersManager {
24+ // 添加衣服款式
25+ static addClothes ( id , gender , clothes ) {
26+ const modal = ModalFactory . create ( id , gender )
27+ this [ id ] = {
28+ clothes,
29+ modal
30+ }
31+ }
32+
33+ // 拍照
34+ static takePhoto ( id ) {
35+ const obj = this [ id ]
36+ console . log ( `${ obj . modal . gender } 模${ obj . modal . name } 穿${ obj . clothes } 拍了照` )
37+ }
38+ }
39+
40+ for ( let i = 0 ; i < 10 ; i ++ ) {
41+ TakeClothersManager . addClothes ( i , '男' , `服装${ i } ` )
42+ TakeClothersManager . takePhoto ( i )
43+ }
44+
45+ for ( let i = 10 ; i < 20 ; i ++ ) {
46+ TakeClothersManager . addClothes ( i , '女' , `服装${ i } ` )
47+ TakeClothersManager . takePhoto ( i )
48+ }
Original file line number Diff line number Diff line change 7373
7474> [ 享元模式(Flyweight Pattern)] ( /Example/Flyweight-Pattern.js )
7575
76+ 定义:减少创建对象的数量,以减少内存占用和提高性能。
77+ 目的:用共享技术有效地支持大量细粒度的对象。
78+ 场景:系统中有大量对象。
79+
7680***
7781
7882##### 行为模式(Behavioral Pattern)
You can’t perform that action at this time.
0 commit comments