C++ Flyweight Pattern | Save Memory with Sharing
이 글의 핵심
C++ Flyweight Pattern. A structural pattern that reduces memory usage when there are many objects by sharing intrinsic state and keeping extrinsic state separate, with practical examples.
What is the Flyweight Pattern?
The Flyweight pattern is a structural design pattern used when there are a large number of similar objects. It works by sharing intrinsic state (common state) while keeping extrinsic state (individual state) separate. This is particularly useful for reducing memory usage when handling repetitive data like characters, fonts, tiles, or particles. It pairs well with other structural patterns like Memory Pool, [Adapter], and Composite, helping you understand its broader applications.
Why use it?
- To reduce memory usage when rendering thousands of identical glyphs, tiles, or skins
- When there are many objects, but only a few properties (like position or color) differ between them
Basic Structure
#include <unordered_map>
#include <string>
#include <memory>
#include <iostream>
// Shared intrinsic state
struct Glyph {
char ch;
int width, height;
// Bitmap data, etc.
Glyph(char c, int w, int h) : ch(c), width(w), height(h) {}
};
class GlyphFactory {
std::unordered_map<char, std::shared_ptr<Glyph>> cache_;
public:
std::shared_ptr<Glyph> get(char c) {
auto it = cache_.find(c);
if (it != cache_.end()) return it->second;
auto g = std::make_shared<Glyph>(c, 8, 16);
cache_[c] = g;
return g;
}
};
// Extrinsic state: position, etc. — passed during method call
void draw(std::shared_ptr<Glyph> g, int x, int y) {
std::cout << "draw '" << g->ch << "' at (" << x << "," << y << ")\n";
}
int main() {
GlyphFactory factory;
auto a = factory.get('A');
auto b = factory.get('B');
auto a2 = factory.get('A'); // Shares the same object
draw(a, 0, 0);
draw(a2, 10, 0); // Same Glyph, different position
return 0;
}
Summary
| Item | Description |
|---|---|
| Purpose | Reduce memory usage when there are many objects by sharing common state |
| Advantages | Reduced memory usage, cache-friendly |
| Disadvantages | Overhead of passing extrinsic state, increased code complexity |
Related Posts: Memory Pool, Adapter Pattern, Composite Pattern.
One-line Summary: Use the Flyweight pattern to share repetitive data like glyphs or tiles and save memory.
## 같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- [C++ Object Pool | "객체 풀" 가이드](/blog/cpp-object-pool/)
- [C++ Memory Pool | "메모리 풀" 가이드](/blog/cpp-memory-pool/)
- [C++ Adapter Pattern 완벽 가이드 | 인터페이스 변환과 호환성](/blog/cpp-adapter-pattern/)
---
---
## 이 글에서 다루는 키워드 (관련 검색어)
C++, Flyweight, design pattern, structural, memory, sharing 등으로 검색하시면 이 글이 도움이 됩니다.