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
57
| // 메모리 효율적인 Flyweight 구현
public class CharacterFlyweight {
private final char character;
private final String fontFamily;
private final int fontSize;
private final Color color;
// 메모리 사용량: 4 + 8 + 4 + 8 = 24 bytes per flyweight
public void render(int x, int y, Graphics g) {
// 외재적 상태 (x, y)는 파라미터로 전달
g.setFont(new Font(fontFamily, Font.PLAIN, fontSize));
g.setColor(color);
g.drawString(String.valueOf(character), x, y);
}
// equals와 hashCode로 동일한 flyweight 식별
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof CharacterFlyweight)) return false;
CharacterFlyweight that = (CharacterFlyweight) obj;
return character == that.character &&
fontSize == that.fontSize &&
Objects.equals(fontFamily, that.fontFamily) &&
Objects.equals(color, that.color);
}
@Override
public int hashCode() {
return Objects.hash(character, fontFamily, fontSize, color);
}
}
// Factory로 Flyweight 인스턴스 관리
public class CharacterFlyweightFactory {
private final Map<String, CharacterFlyweight> flyweights = new ConcurrentHashMap<>();
public CharacterFlyweight getFlyweight(char character, String fontFamily,
int fontSize, Color color) {
String key = character + "|" + fontFamily + "|" + fontSize + "|" + color.getRGB();
return flyweights.computeIfAbsent(key, k ->
new CharacterFlyweight(character, fontFamily, fontSize, color)
);
}
public int getFlyweightCount() {
return flyweights.size();
}
// 메모리 사용량 분석:
// 일반 구현: 1,000,000 문자 = 24MB
// Flyweight: 100 고유 문자 = 2.4KB + 컨텍스트 8MB = 8.0024MB
// 메모리 절약: 67%
}
|