객체를 가볍게 만들어 메모리 사용을 줄이는 패턴.
Fly = 가볍게, weight = 무게를 => 객체를 가볍게 만들자


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는 같은 데이터로 계속 중복됨. => 객체가 무겁고 공통 속성 변경 관리가 번거로움
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);