typescript: Flyweight Pattern

 

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
/**
 * Flyweight Pattern 享元是一种结构型设计模式, 它允许你在消耗少量内存的情况下支持大量对象。
 * https://refactoringguru.cn/design-patterns/flyweight/typescript/example#lang-features
 * The Flyweight stores a common portion of the state (also called intrinsic
 * state) that belongs to multiple real business entities. The Flyweight accepts
 * the rest of the state (extrinsic state, unique for each entity) via its
 * method parameters.
 */
 
 
class Flyweight {
 
    /**
     *
     */
    private sharedState: any;
     
    /**
     *
     * @param sharedState
     */
    constructor(sharedState: any) {
        this.sharedState = sharedState;
    }
    /**
     *
     * @param uniqueState
     */
    public operation(uniqueState):string {  //void
        let str="";
        const s = JSON.stringify(this.sharedState);
        const u = JSON.stringify(uniqueState);
        console.log(`Flyweight: Displaying shared (${s}) and unique (${u}) state.`);
        str=str+s+","+u;
        return str;
    }
}
 
/**
 * The Flyweight Factory creates and manages the Flyweight objects. It ensures
 * that flyweights are shared correctly. When the client requests a flyweight,
 * the factory either returns an existing instance or creates a new one, if it
 * doesn't exist yet.
 */
class FlyweightFactory {
    /**
     *
     */
    private flyweights: {[key: string]: Flyweight} = <any>{};
 
    /**
     *
     * @param initialFlyweights
     */
    constructor(initialFlyweights: string[][]) {
        for (const state of initialFlyweights) {
            this.flyweights[this.getKey(state)] = new Flyweight(state);
        }
    }
 
    /**
     * Returns a Flyweight's string hash for a given state.
     */
    private getKey(state: string[]): string {
        return state.join('_');
    }
 
    /**
     * Returns an existing Flyweight with a given state or creates a new one.
     */
    public getFlyweight(sharedState: string[]): Flyweight {
        const key = this.getKey(sharedState);
 
        if (!(key in this.flyweights)) {
            console.log('FlyweightFactory: Can\'t find a flyweight, creating new one.');
            this.flyweights[key] = new Flyweight(sharedState);
        } else {
            console.log('FlyweightFactory: Reusing existing flyweight.');
        }
 
        return this.flyweights[key];
    }
    /**
     *
     */
    public listFlyweights():string { //void
        let str="";
        const count = Object.keys(this.flyweights).length;
        console.log(`\nFlyweightFactory: I have ${count} flyweights:`);
        for (const key in this.flyweights) {
            console.log(key);
            str=str+","+key;
        }
 
        return str;
    }
}
 
/**
 * The client code usually creates a bunch of pre-populated flyweights in the
 * initialization stage of the application.
 */
const factory = new FlyweightFactory([
    ['Chevrolet', 'Camaro2018', 'pink'],
    ['Mercedes Benz', 'C300', 'black'],
    ['Mercedes Benz', 'C500', 'red'],
    ['BMW', 'M5', 'red'],
    ['BMW', 'X6', 'white'],
    // ...
]);
let pubf1="";
let pubf2="";
let pubf3="";
let pubf4="";
 
pubf3=factory.listFlyweights();
 
// ...
/**
 *
 * @param ff
 * @param plates
 * @param owner
 * @param brand
 * @param model
 * @param color
 */
function addCarToPoliceDatabase(
    ff: FlyweightFactory, plates: string, owner: string,
    brand: string, model: string, color: string,
) {
    console.log('\nClient: Adding a car to database.');
    const flyweight = ff.getFlyweight([brand, model, color]);
 
    // The client code either stores or calculates extrinsic state and passes it
    // to the flyweight's methods.
   return flyweight.operation([plates, owner]);
 
 
}
 
pubf1=addCarToPoliceDatabase(factory, 'CL234IR', 'James Doe', 'BMW', 'M5', 'red');
 
pubf2=addCarToPoliceDatabase(factory, 'CL234IR', 'James Doe', 'BMW', 'X1', 'red');
 
pubf4=factory.listFlyweights();
 
 
 
let messageflyweight: string = 'Hello World,This is a typescript!,涂聚文 Geovin Du.Web';
document.body.innerHTML = messageflyweight+",<br/>one="+pubf1+",<br/>two="+pubf2+",<br/>thee="+pubf3+",<br/>four="+pubf4+",<br/>TypeScript Flyweight Pattern 享元模式";

  

调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <head><title>TypeScript Hello Flyweight Pattern 享元模式</title>
      <meta name="Description" content="geovindu,涂聚文,Geovin Du"/>
<meta name="Keywords" content="geovindu,涂聚文,Geovin Du"/>
<meta name="author" content="geovindu,涂聚文,Geovin Du"/>
    </head>
    <body>
        <script src="dist/Flyweightts.js"></script>
    </body>
</html>

  

 

输出:

 

posted @   ®Geovin Du Dream Park™  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2022-10-10 CSharp: State Pattern in donet core 3
2022-10-10 CSharp: Memento Pattern in donet core 3
2022-10-10 CSharp: Iterator Pattern in donet core 3
2014-10-10 String Control
2013-10-10 Csharp:user WebControl Read Adobe PDF Files In Your Web Browser
2009-10-10 What Is Web 2.0
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示