April 12, 2022
01.패턴적용해보기
01.1 Font.java 생성
01.2 Character.java 생성
01.3 FontFactory.java 생성
01.4 Client.java
자주 바뀐다와 바뀌지 않는 것은 완전히 주관적이고 상황에 따라 바뀜
pulblic 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{
char value;
String color;
Font font;
public Character(char value, String color, Font font){
this.value = value;
this.color = color;
this.font = font;
}
}
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;
}
}
}
before
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);
}
}
after
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"));
}
}