Flyweight - a.k.a Cache
메모리 절약하기
Intent
Flyweight is a structural design pattern that lets you fit more objects into the available amount of RAM by sharing common parts of state between multiple objects instead of keeping all of the data in each object.
Implementation

Applicablity
- 캐싱
Code Examples
package oodesign.design.structural.flyweight; public class Flyweight { public Flyweight(String data) { this.data = data; } private String data; public String getData(){ return data; } }
package oodesign.design.structural.flyweight; import java.util.Map; import java.util.TreeMap; public class FlyweightFactory { Map<Long, Flyweight> pool; public FlyweightFactory() { this.pool = new TreeMap(); } public Flyweight getFlyweight(Long key){ Flyweight flyweight = pool.get(key); if(flyweight == null){ flyweight = new Flyweight(String.valueOf(key)); pool.put(key, flyweight); System.out.println("new " + key); }else{ System.out.println("reuse " + key); } return flyweight; } }
package oodesign.design.structural.flyweight; public class Main { public static void main(String[] args) { FlyweightFactory factory = new FlyweightFactory(); System.out.println("flyweight = " + factory.getFlyweight(1L)); System.out.println("flyweight = " + factory.getFlyweight(1L)); System.out.println("flyweight = " + factory.getFlyweight(1L)); System.out.println("flyweight = " + factory.getFlyweight(2L)); } }
실행 결과
new 1 flyweight = oodesign.design.structural.flyweight.Flyweight@3498ed reuse 1 flyweight = oodesign.design.structural.flyweight.Flyweight@3498ed reuse 1 flyweight = oodesign.design.structural.flyweight.Flyweight@3498ed new 2 flyweight = oodesign.design.structural.flyweight.Flyweight@1a407d53 Process finished with exit code 0