디자인 패턴

자바(JAVA) - 플라이 웨이트(Flyweight) 패턴

Hyeongjun_Ham 2023. 11. 16. 10:22

- 자바(JAVA) - 플라이 웨이트(Flyweight) 패턴

 

1. 의도

동일하거나 유사한 객체들 사이에 가능한 많은 데이터를 서로 공유해서 사용하도록 하여 메모리 사용량을 최소화하는 소프트웨어 디자인 패턴

2. 용도

주로 메모리 사용량을 줄여서 효율성을 높일 때 사용

 

3. UML

 

4. 구현

public class Font {

    final String family;

    final int size;

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

=========================================================================
public class FontFactory {

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

    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;
        }
    }
}

=========================================================================
public class Character {

    private final char value;
    private final String color;
    private final Font font;

    public Character(char value, String color, Font font) {
        this.value = value;
        this.color = color;
        this.font = font;
    }
	// 비교를 위해 만듬
    public Character(char value, String color, String fontFamily, int fontSize) {
        this.value = value;
        this.color = color;
        this.font = new Font(fontFamily, fontSize);
    }

    public Font getFont() {
        return 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('i', "white", fontFactory.getFont("nanum:12"));

        System.out.println(c1.getFont());
        System.out.println(c2.getFont());
        System.out.println(c3.getFont());

        Character c4 = new Character('h', "white", "nanum", 12);
        Character c5 = new Character('h', "white", "nanum", 12);
        Character c6 = new Character('h', "white", "nanum", 12);

        System.out.println(c4.getFont());
        System.out.println(c5.getFont());
        System.out.println(c6.getFont());
    }
}

//결과 
/*
c1 : org.example.flyweight.Font@59f95c5d
c2 : org.example.flyweight.Font@59f95c5d
c3 : org.example.flyweight.Font@59f95c5d

c4 : org.example.flyweight.Font@5c8da962
c5 : org.example.flyweight.Font@512ddf17
c6 : org.example.flyweight.Font@2c13da15
*/

 

재사용하는 것을 볼 수 있다.

5. 패턴의 장단점

  • 장점
    • 애플리케이션에서 사용하는 유사한 객체들이 많은 경우 메모리 사용량을 줄일 수 있다.
  • 단점
    • 특정 인스턴스만 다른 인스턴스처럼 동작하도록 하는 것이 불가능
    • 객체의 값을 변경하면 공유받은 객체를 사용하는 곳에 영향을 줄 수 있다.

 

출처 :

https://refactoring.guru/design-patterns/flyweight

 

Flyweight

/ Design Patterns / Structural Patterns Flyweight Also known as: Cache Intent Flyweight is a structural design pattern that lets you fit more objects into the available amount of RAM by sharing common parts of state between multiple objects instead of keep

refactoring.guru