구조 패턴: 플라이 웨이트 패턴

xellos·2022년 4월 7일
0

디자인 패턴

목록 보기
12/20

소개

객체를 가볍게 만들어 메모리 사용을 줄이는 패턴이다.

  • 자주 변하는 속성(또는 외적인 속성)과 변하지 않는 속성(또는 내적인 속성)을 분리하고 재사용하여 메모리 사용을 줄일 수 있다.

1) 장점

애플리케이션에서 사용하는 메모리를 줄일 수 있다.

2) 단점

코드의 복잡도가 증가한다.


적용전

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);
    }
}

구현

1) 팩토리 생성

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;
        }
    }
}

2) 내적 요소 정의

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;
    }
}

3) 외적 요소 정의

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");
    }
}

0개의 댓글