Skip to content

Instantly share code, notes, and snippets.

@semlinker
Created October 23, 2022 15:23
Show Gist options
  • Save semlinker/c897f9764ddc43c7e240578dd5c131e9 to your computer and use it in GitHub Desktop.
Save semlinker/c897f9764ddc43c7e240578dd5c131e9 to your computer and use it in GitHub Desktop.
Design Patterns: Flyweight Pattern in TypeScript
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