티스토리 뷰

디자인 패턴

11. 플라이 웨이트 패턴

jin-park 2022. 2. 10. 17:51

1.  플라이 웨이트(FlyWeight) 패턴

  • 객체를 가볍게 만들어 메모리 사용을 줄이는 패턴.
  • 자주 변하는 속성과 변하지 않는 속성을 분리하고 재사용하여 메모리 사용을 줄일 수 있다.

다이어그램

2.  패턴 적용 전 코드

  • Character를 생성시 중복되는 파라미터가 존재함. (fontFamily, fontSize)
    • 중복은 상황과 생각에 따라 다르게 결정될 수 있음.
public class Character {
    private String value;
    private String color;
    private String fontFamily;
    private Integer fontSize;
 
    public Character(String value, String color, String fontFamily, Integer fontSize) {
        this.value = value;
        this.color = color;
        this.fontFamily = fontFamily;
        this.fontSize = fontSize;
    }
}
public class Client {
    public static void main(String[] args) {
        Character character1 = new Character("h", "white", "Nanum", 12);
        Character character2 = new Character("e", "white", "Nanum", 12);
        Character character3 = new Character("l", "white", "Nanum", 12);
        Character character4 = new Character("l", "white", "Nanum", 12);
        Character character5 = new Character("o", "white", "Nanum", 12);
    }
}

3.  패턴 적용

  • Font 객체는 공유 객체이므로 한 부분에서 수정될 경우 모든 객체에 적용되므로 불변(immutable)하게 만들어준다.
  • FontFactory를 통해 Font를 생성하며 캐싱기능을 제공하여 중복되는 메모리 사용을 줄여준다.
public final class Font {
    private final String family;
    private final Integer fontSize;
 
    public Font(String family, Integer fontSize) {
        this.family = family;
        this.fontSize = fontSize;
    }
 
    public String getFamily() { return family; }
    public Integer getFontSize() { return fontSize; }
}
public class FontFactory {
    private Map<String, Font> cache = new HashMap<>();
 
    public Font getFont(String fontName) {
        if (this.cache.containsKey(fontName)) {
            return this.cache.get(fontName);
        }
 
        String[] split = fontName.split(":");
        Font font = new Font(split[0], Integer.parseInt(split[1]));
        cache.put(fontName, font);
 
        return font;
    }
}
public class FlyweightClient {
    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"));
        Character c4 = new Character("l", "white", fontFactory.getFont("nanum:12"));
        Character c5 = new Character("o", "white", fontFactory.getFont("nanum:12"));
    }
}

4.  장점 및 단점

4.1.  장점

  • 애플리케이션에서 사용하는 메모리 사용량을 줄여 줄 수 있다. (캐싱)

4.2.  단점

  • 애플리케이션 계층의 복잡도가 상승함다. (코드 작성 내용 공유 필요)

'디자인 패턴' 카테고리의 다른 글

13. 책임연쇄패턴  (0) 2022.02.10
12. 프록시 패턴  (0) 2022.02.10
10. 퍼사드 패턴  (0) 2022.02.10
09. 데코레이터 패턴  (0) 2022.02.10
08. 컴포짓 패턴  (0) 2022.02.10
댓글