728x90
반응형
01.패턴적용해보기
- 자주 바뀐다와 바뀌지 않는 것은 완전히 주관적이고 상황에 따라 바뀜
- 정답이 있는 것은 아님
- 여기서는 fontFamily와 fontSize를 플라이웨이트 객체화 할 것
01.1 Font.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;
}
}
- 주의 할 것은 플라이웨이트에 해당하는 인스턴스는 immutable 해야함 변경이 되면 안됨
- 공유 데이터라서 바뀌면 절대 안됨
01.2 Character.java 생성
public class Character{
char value;
String color;
Font font;
public Character(char value, String color, Font font){
this.value = value;
this.color = color;
this.fonr = font;
}
}
01.3 FontFactory.java 생성
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(regex:":");
Font newFont = new Font(split[0], Integer.parseInt(split[1]));
cache.put(font, newFont);
return newFont;
}
}
}
01.4 Client.java
- 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")); } }
22-04-12-플라이웨이트패턴-2부-패턴적용하기
22-04-12-플라이웨이트패턴-2부-패턴적용하기
3dpit.github.io
728x90
반응형
'CS Study > 디자인패턴' 카테고리의 다른 글
22-04-12-플라이웨이트패턴-4부-자바와스프링에서찾아보는패턴 (0) | 2022.04.12 |
---|---|
22-04-12-플라이웨이트패턴-3부-장점과단점 (0) | 2022.04.12 |
22-04-12-플라이웨이트패턴-1부-패턴소개 (0) | 2022.04.12 |
22-04-11-비지터패턴-4부-자바와스프링에서찾아보는패턴 (0) | 2022.04.12 |
22-04-11-비지터패턴-3부-장점과단점 (0) | 2022.04.12 |
댓글