객체를 가볍게 만들어 메모리 사용을 줄이는 패턴이다.
애플리케이션에서 사용하는 메모리를 줄일 수 있다.
코드의 복잡도가 증가한다.
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);
}
}
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[] splist = font.split(":");
Font newFont = new Font(split[0], Integer.parseInt(split[1]));
cache.put(font, newFont);
return newFont;
}
}
}
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 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");
Character c4 = new Character('l', "white", fontFactory.getFont("nanum:12");
Character c5 = new Character('o', "white", fontFactory.getFont("nanum:12");
}
}