학습목표

  • 공유 가능한 객체를 재사용하여 메모리 사용 최적화 원리 이해
  • 내부 상태(공유) / 외부 상태(비공유)의 개념 구분
  • 객체가 대량으로 생성될 때 플라이웨이트가 왜 필요한지 파악
  • 팩토리(캐싱) 방식으로 객체를 관리하는 구조 습득

활용방법

  • 문서에 같은 글자 수천 개 → 폰트 공유
  • 수십만 개 미니언 모델 → Texture/Mesh 공유
  • 건물 아이콘, 마커 공유
  • DB Connection, 상수 문자열 재사용

⇒ Java String Pool, JDBC connection Pool

 

예제

더보기

문서 내 동일한 Font 스타일이 반복되는 경우 → Font 객체를 공유

  • Font ( Flyweight 객체 (내부 상태) )
public class Font {
    private final String fontName;
    private final int size;

    public Font(String fontName, int size) {
        this.fontName = fontName;
        this.size = size;
    }

    public String getFontName() { return fontName; }
    public int getSize() { return size; }
}
  • FontFactory ( Flyweight Factory (캐싱 저장) )
public class FontFactory {
    private static final Map<String, Font> fontPool = new ConcurrentHashMap<>();

    public static Font getFont(String name, int size) {
        String key = name + size;
        fontPool.putIfAbsent(key, new Font(name, size));
        return fontPool.get(key);
    }

    public static int getPoolSize() {
        return fontPool.size();
    }
}
  • CharacterGlyph ( 외부 상태는 글자 위치로 전달 )
public class CharacterGlyph {
    private final char value;
    private final Font font; // 공유
    private final int x;     // 비공유
    private final int y;     // 비공유

    public CharacterGlyph(char value, Font font, int x, int y) {
        this.value = value;
        this.font = font;
        this.x = x;
        this.y = y;
    }

    public void draw() {
        System.out.println("Draw '" + value + "' at (" + x + "," + y +
                ") with font: " + font.getFontName() + "-" + font.getSize());
    }
}

 

  • 실행
public class Main {
    public static void main(String[] args) {
        Font fontArial12 = FontFactory.getFont("Arial", 12);
        Font fontArial12Again = FontFactory.getFont("Arial", 12);

        System.out.println(fontArial12 == fontArial12Again); // true (공유 객체)

        new CharacterGlyph('A', fontArial12, 10, 10).draw();
        new CharacterGlyph('B', fontArial12, 20, 10).draw();

        System.out.println(FontFactory.getPoolSize()); // 1
    }
}

- FontFactory에서 Font를 불러올 때 이름과 사이즈만 같으면 재생성하지 않고 값을 공유해서 쓰이는 점 메모리 효율을 높입니다.

 

마무리

위에 예제 처럼 값 자체가 바뀌지 않는 다면 메모리가 공유되어서 효율이 올라가는 장점이 있습니다.

'Java > 패턴' 카테고리의 다른 글

커맨드 패턴 ( Command Pattern )  (1) 2025.12.11
프록시 패턴 ( Proxy Pattern )  (0) 2025.12.10
메멘토 패턴 ( Memento Pattern )  (0) 2025.12.08
상태 패턴 ( State Pattern )  (0) 2025.12.05
중재자 패턴 ( Mediator Pattern )  (0) 2025.12.04

+ Recent posts