15 minpresentation
Flyweight Implementation
Flyweight Implementation
0 / 7 completedFactory Pattern for Flyweights
typescript1class 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: boolean8 ) {9 Object.freeze(this); // Ensure immutability10 }11}1213class PostalCodeFactory {14 private cache = new Map<string, PostalCodeInfo>();15 private stats = { hits: 0, misses: 0 };1617 get(postalCode: string): PostalCodeInfo {18 if (this.cache.has(postalCode)) {19 this.stats.hits++;20 return this.cache.get(postalCode)!;21 }2223 this.stats.misses++;24 const info = this.lookup(postalCode);25 this.cache.set(postalCode, info);26 return info;27 }2829 private lookup(postalCode: string): PostalCodeInfo {30 // Simulated database/API lookup31 return new PostalCodeInfo(32 'City Name',33 'ST',34 'County Name',35 'America/New_York',36 true37 );38 }3940 getCacheStats() {41 return { ...this.stats, size: this.cache.size };42 }43}
Step 1 of 7
← → NavigateSpace: Skip / NextEnter: Next