-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflyweight.ts
56 lines (47 loc) · 1.27 KB
/
flyweight.ts
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
/**
* Represents a character that can be drawn on the screen.
*/
interface Letter {
draw(row: number, col: number): void;
getChar(): string;
}
/**
* Represents a single character that can be drawn on the screen.
* This class implements the `Letter` interface to provide a consistent
* drawing API for characters.
*/
class Character implements Letter {
private char: string;
constructor(char: string) {
this.char = char;
}
draw(row: number, col: number): void {
console.log(`Drawing ${this.char} at ${row}, ${col}`);
}
getChar(): string {
return this.char;
}
}
/**
* A factory class that manages the creation and reuse of `Letter` objects.
* This class implements the Flyweight pattern to optimize memory usage by
* sharing common `Letter` instances.
*/
class LetterFactory {
private letters: { [key: string]: Letter } = {};
constructor() {}
createLetter(char: string): Letter {
if (!this.letters[char]) {
this.letters[char] = new Character(char);
}
return this.letters[char];
}
getLetterCount(): number {
return Object.keys(this.letters).length;
}
getLetters(): string[] {
return Object.values(this.letters).map((letter) => letter.getChar());
}
//... Other APIs
}
export { Character, Letter, LetterFactory };