본문 바로가기
java

Design Patterns - Flyweight

by 쭈꾸마뇽 2021. 12. 21.

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

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

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;
    }
}
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 클래스에서 사용하는 Font 클래스를 만들어주는데 이 클래스는 immutable 해야 한다.  왜냐하면 여러 객체에서 공유하기 때문에 변경이 가능하면 다른 객체에 영향을 줄 수 있기 때문이다

public class FontFactory {

    private final Map<String, Font> cache = new HashMap<>();

    public Font getFont(String font) {
        if (cache.containsKey(font)) {
            return cache.get(font);
        }

        String[] split = font.split(":");
        Font newFont = new Font(split[0], Integer.parseInt(split[1]));
        cache.put(font, newFont);
        return newFont;
    }
}

Font를 저장해두고 꺼내올수 있는 FontFactory를 만들어준다.  이미 만들어진 Font가 있다면 캐시에서 꺼내오고 아니라면 새로 만들어 캐시에 저장한 다음 리턴해준다

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"));
    }
}
  • 장점
    • 애플리케이션에서 사용하는 메모리를 줄일 수 있다
  • 단점
    • 코드의 복잡도가 증가한다

 

 

코딩으로 학습하는 GoF의 디자인 패턴 - 인프런 | 강의

디자인 패턴을 알고 있다면 스프링 뿐 아니라 여러 다양한 기술 및 프로그래밍 언어도 보다 쉽게 학습할 수 있습니다. 또한, 보다 유연하고 재사용성이 뛰어난 객체 지향 소프트웨어를 개발할

www.inflearn.com

 

'java' 카테고리의 다른 글

Design Patterns - Chain of Responsibility  (0) 2022.01.30
Design Patterns - Proxy  (0) 2022.01.16
Design Patterns - Facade  (0) 2021.12.10
Design Patterns - Decorator  (0) 2021.12.04
Design Patterns - Composite  (0) 2021.11.29

댓글