22-04-12-플라이웨이트패턴-2부-패턴적용하기
본문 바로가기
CS Study/디자인패턴

22-04-12-플라이웨이트패턴-2부-패턴적용하기

by KyeongMin 2022. 4. 12.
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"));
        }
    }

https://3dpit.github.io/posts/%ED%94%8C%EB%9D%BC%EC%9D%B4%EC%9B%A8%EC%9D%B4%ED%8A%B8%ED%8C%A8%ED%84%B4-2%EB%B6%80-%ED%8C%A8%ED%84%B4%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0/

 

22-04-12-플라이웨이트패턴-2부-패턴적용하기

22-04-12-플라이웨이트패턴-2부-패턴적용하기

3dpit.github.io

 

728x90
반응형

댓글