Design Pattern_Structural Patterns_Flyweight

박지홍·2026년 4월 13일

DesignPattern

목록 보기
8/12

플라이웨이드 패턴

객체를 가볍게 만들어 메모리 사용을 줄이는 패턴.

Fly = 가볍게, weight = 무게를 => 객체를 가볍게 만들자

  • 자주 변하는 속성(또는 외적인 속성, extrinsit)과 변하지 않는 속성(또는 내적인 속성, intrinsit)을 분리하고 재사용하여 메모리 사용을 줄일 수 있다.

적용

befor

Character.java

public class Character {

    private char value;

    private String color;

    private String fontFamily;

    private int fontSize;

    public Character(char value, String color, String fontFamily, int fontSize) {
        this.value = value;
        this.color = color;
        this.fontFamily = fontFamily;
        this.fontSize = fontSize;
    }
}

Client.java

public class Client {

    public static void main(String[] args) {
        Character c1 = new Character('h', "white", "Nanum", 12);
        Character c2 = new Character('e', "white", "Nanum", 12);
        Character c3 = new Character('l', "white", "Nanum", 12);
        Character c4 = new Character('l', "white", "Nanum", 12);
        Character c5 = new Character('o', "white", "Nanum", 12);
    }
}

문제점: white, nanum과 12는 같은 데이터로 계속 중복됨. => 객체가 무겁고 공통 속성 변경 관리가 번거로움

after

Font

public final class Font {

    final String family;

    final int size;

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

    public String getFamily() {
        return family;
    }

    public int getSize() {
        return size;
    }
}

Character

public class Character {

    private char value;

    private String color;

    private Font font;

    public Character(char value, String color, Font font) {
        this.value = value;
        this.color = color;
        this.font = font;
    }
}

FontFactory

public class FontFactory {

    private Map<String, Font> cache = new HashMap<>(); // 만들어둔 Font 객체 저장

    public Font getFont(String font) { // 이미 있으면 기존것 반환, 없으면 새로 저장 후 반환
        if (cache.containsKey(font)) {
            return cache.get(font);
        } else {
            String[] split = font.split(":");
            Font newFont = new Font(split[0], Integer.parseInt(split[1]));
            cache.put(font, newFont);
            return newFont;
        }
    }
}

이미 만든 font가 있으면 재사용, 없으면 새로 만들고 재사용

Client.java

public class Client {

    public static void main(String[] args) {
        FontFactory fontFactory = new FontFactory();
        Character c1 = new Character('h', "white", fontFactory.getFont("nanum:12"));
        Character c2 = new Character('e', "white", fontFactory.getFont("nanum:12"));
        Character c3 = new Character('l', "white", fontFactory.getFont("nanum:12"));
    }
}

장단점

  • 장점

    • 중복 객체 생성을 줄여 애플리케이션에서 사용하는 메모리를 줄일 수 있다.
    • 공통 상태를 한 곳에서 관리할 수 있다.
  • 단점

    • 객체, 팩토리, 캐시를 도입해 코드의 복잡도가 증가한다.

=> 메모리 최적화가 중요하고, 비슷한 객체를 엄청 많이 만들어야 할 때 유용하다.

자바에서 예제 찾기

Integer i1 = Integer.valueOf(10);
Integer i2 = Integer.valueOf(10);
System.out.println(i1 == i2);

0개의 댓글