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

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

목차

01.패턴적용해보기

01.1 Font.java 생성

01.2 Character.java 생성

01.3 FontFactory.java 생성

01.4 Client.java

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.font = 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(":");
            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"));
      }
    }
    • 이런식으로 성능을 개선
    • 인스턴스를 많이 쓰는 경우 사용함

Written by@[KyeongMinPark]
Docker, C++, C#, Java, Golang으로 개발 모니터링운영 및 개발, 자원수집기 Beat & Exporter 개발 Gitlab Runner CI/CD & Hugo 연동과 테스트코드및 등을 공부와 개발중 ORM, TDD, BDD, DDD, DesignPattern, WebAssembly Studying

GitHub