PDHBE / study

기술 서적 Study
0 stars 0 forks source link

[GoF 디자인패턴] 플라이웨이트 (Flyweight) 패턴 #16

Open leeyuunsung opened 2 years ago

leeyuunsung commented 2 years ago

플라이웨이트 패턴 1부 - 패턴 소개

패턴 다이어그램

스크린샷 2021-12-04 오후 3 32 32

문제 상황

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

플라이웨이트 패턴 2부 - 패턴 적용하기

플라이웨이트 패턴 적용

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;
    }
}
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 class FontFactory {

    private 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 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"));
    }
}
leeyuunsung commented 2 years ago

플라이웨이트 패턴 3부 - 장점과 단점

장점

단점


플라이웨이트 패턴 4부 - 자바와 스프링에서 찾아보는 패턴

public static void main(String[] args) {
    Integer i1 = Integer.valueOf(10);
    Integer i2 = Integer.valueOf(10);
    System.out.println(i1 == i2); // True
}

Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range. Params: i – an int value. Returns: an Integer instance representing i. Since: 1.5