Created
October 23, 2022 15:23
-
-
Save semlinker/c897f9764ddc43c7e240578dd5c131e9 to your computer and use it in GitHub Desktop.
Design Patterns: Flyweight Pattern in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UPhoneFlyweight { | |
constructor(model: string, screen: number, memory: number) {} | |
} | |
class FlyweightFactory { | |
public phonesMap: Map<string, UPhoneFlyweight> = new Map(); | |
public get(model: string, screen: number, memory: number): UPhoneFlyweight { | |
const key = model + screen + memory; | |
if (!this.phonesMap.has(key)) { | |
this.phonesMap.set(key, new UPhoneFlyweight(model, screen, memory)); | |
} | |
return this.phonesMap.get(key)!; | |
} | |
} | |
class UPhone { | |
constructor(flyweight: UPhoneFlyweight, sn: number) {} | |
} | |
class UPhoneFactory { | |
public static flyweightFactory: FlyweightFactory = new FlyweightFactory(); | |
public getUPhone(model: string, screen: number, memory: number, sn: number) { | |
const flyweight: UPhoneFlyweight = UPhoneFactory.flyweightFactory.get( | |
model, | |
screen, | |
memory | |
); | |
return new UPhone(flyweight, sn); | |
} | |
} | |
const uphoneFactory = new UPhoneFactory(); | |
let uphones = []; | |
for (let i = 0; i < 10000; i++) { | |
let memory = i % 2 == 0 ? 64 : 128; | |
uphones.push(uphoneFactory.getUPhone("8U", 5.0, memory, i)); | |
} | |
console.log( | |
"UPhoneFlyweight count:", | |
UPhoneFactory.flyweightFactory.phonesMap.size | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment