Notice
Recent Posts
Recent Comments
Link
개발자는 기록이 답이다
플라이웨이트 패턴 본문

플라이웨이트 : 자주 변경되는 값과 아닌 값을 분리해서 재사용하는 방식이다.
아래 내용처러 문제에 대해 정의한 클래스가 있다고 가정해보자.
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;
}
}
위의 코드는 너무 무겁다.
자주 변경되지 않은 fontFamily와 fontSize를 묶어서 Font클래스에 담아주고, FontFactory에서 값을 가져와서 재사용하는 방식으로 해보자.
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 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;
}
}
import java.util.HashMap;
import java.util.Map;
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"));
}
}