HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
📝
남득윤 학습 저장소
/
객체 지향 프로그래밍
객체 지향 프로그래밍
/
디자인 패턴
디자인 패턴
/
Flyweight Pattern
Flyweight Pattern
Flyweight Pattern

Flyweight Pattern

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

notion image

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