728x90
반응형
Flyweight Pattern
객체를 가볍게 만들어 메모리 사용을 줄이는 패턴
자주 변하는 속성(또는 외적인 속성, extrinsit)과 변하지 않는 속성(또는 내적인 속성, instrinsit)을 분리하고 재사용하여 메모리 사용을 줄일 수 있다.
BEFORE
Client
- 현재 INTIP 웹 서비스에 게시판 에디터 부분이 아래처럼 되어 있는데, 해당 패턴을 활용하면 성능을 향상시킬 수 있겠다.
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);
}
}
Character
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;
}
}
AFTER
Client
- FontFactory를 사용하면, 기존의 등록되어 있는 데이터를 찾아서 반영할 때 성능적인 이점을 얻을 수 있겠다. 오호!
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
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<>();
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;
}
}
}
FontFamily
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;
}
}
[패턴 복습]
장점 | 단점 |
- 애플리케이션에서 사용하는 메모리를 줄일 수 있다. | - 코드의 복잡도가 증가한다. |
[실무에서 쓰이는 경우]
- 자바
- Integer.valueOf(int)
- 캐시를 제공한다.
- https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#valueOf-int-
728x90
반응형
'Design Patterns > 구조(Structural)' 카테고리의 다른 글
[Proxy]프록시패턴 (0) | 2022.10.19 |
---|---|
[Facade]퍼사드패턴 (0) | 2022.10.18 |
[Decorator]데코레이터패턴 (0) | 2022.08.01 |
[Composite]컴포짓패턴 (0) | 2022.08.01 |
[Bridge]브릿지패턴 (0) | 2022.08.01 |