15 minpresentation

Flyweight Implementation

Flyweight Implementation

0 / 7 completed

Factory Pattern for Flyweights

typescript
1class PostalCodeInfo {
2 constructor(
3 public readonly city: string,
4 public readonly state: string,
5 public readonly county: string,
6 public readonly timezone: string,
7 public readonly dstObserved: boolean
8 ) {
9 Object.freeze(this); // Ensure immutability
10 }
11}
12
13class PostalCodeFactory {
14 private cache = new Map<string, PostalCodeInfo>();
15 private stats = { hits: 0, misses: 0 };
16
17 get(postalCode: string): PostalCodeInfo {
18 if (this.cache.has(postalCode)) {
19 this.stats.hits++;
20 return this.cache.get(postalCode)!;
21 }
22
23 this.stats.misses++;
24 const info = this.lookup(postalCode);
25 this.cache.set(postalCode, info);
26 return info;
27 }
28
29 private lookup(postalCode: string): PostalCodeInfo {
30 // Simulated database/API lookup
31 return new PostalCodeInfo(
32 'City Name',
33 'ST',
34 'County Name',
35 'America/New_York',
36 true
37 );
38 }
39
40 getCacheStats() {
41 return { ...this.stats, size: this.cache.size };
42 }
43}
Step 1 of 7
← → NavigateSpace: Skip / NextEnter: Next