플라이웨이트 패턴
- 메모리 사용을 최소화하면서 많은 객체를 효율적으로 지원하기 위해 사용되는 구조 디자인 패턴
- 대량의 작은 객체를 생성하는 경우 유용하며 객체의 상태를 자주 변하는 속성(Extrinsit)과 변하지 않는 속성(Intrinsit)으로 분리하여 공통된 내재 상태를 공유함으로써 메모리 사용을 줄임

주요 구성 요소
1. Flyweight 인터페이스
- 모든 Flyweight 클래스가 구현해야 하는 인터페이스로 주로 자주 변하는 속성(Extrinsit)을 인자로 받는 메서드를 정의
2. ConcreteFlyweight 클래스
- Flyweight 인터페이스 구현체
- 변하지 않는 속성(Intrinsit)을 저장
3. FlyweightFactory 클래스
- Flyweight 객체를 생성하고 관리하는 역할
- 요청된 Flyweight가 이미 존재하면 캐시에서 반환하고 존재하지 않으면 새로 생성하여 반환
4. Client
- Flyweight 객체를 사용하는 클라이언트
- 자주 변하는 속성(Extrinsit)을 관리하고 Flyweight 객체에 이를 전달
플라이웨이트 패턴 구현 예시
1. Flyweight 인터페이스
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Flyweight { | |
void operation(String extrinsicState); | |
} |
2. ConcreteFlyweight 클래스
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ConcreteFlyweight implements Flyweight { | |
private final String intrinsicState; | |
public ConcreteFlyweight(String intrinsicState) { | |
this.intrinsicState = intrinsicState; | |
} | |
@Override | |
public void operation(String extrinsicState) { | |
System.out.println(String.format("변하지 않는 속성 %s, 자주 변하는 속성 %s", intrinsicState, extrinsicState)); | |
} | |
} |
3. FlyweightFactory 클래스
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FlyweightFactory { | |
private final Map<String, Flyweight> flyweightPool = new HashMap<>(); | |
public Flyweight getFlyweight(String intrinsicState) { | |
if (!flyweightPool.containsKey(intrinsicState)) { | |
flyweightPool.put(intrinsicState, new ConcreteFlyweight(intrinsicState)); | |
} | |
return flyweightPool.get(intrinsicState); | |
} | |
} |
4. Client 코드
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Client { | |
public static void main(String[] args) { | |
FlyweightFactory factory = new FlyweightFactory(); | |
Flyweight flyweight1 = factory.getFlyweight("변하지 않는 속성 1"); | |
Flyweight flyweight2 = factory.getFlyweight("변하지 않는 속성 2"); | |
Flyweight flyweight3 = factory.getFlyweight("변하지 않는 속성 1"); | |
// 자주 변하는 속성 | |
flyweight1.operation("X"); | |
flyweight2.operation("Y"); | |
flyweight3.operation("Z"); | |
System.out.println("flyweight1 == flyweight3: " + (flyweight1 == flyweight3)); | |
} | |
} |

플라이웨이트 패턴 장단점
장점
- 공유 가능한 객체를 캐싱을 통해 재사용함에 따라 메모리 사용량을 줄일 수 있음
단점
- 객체의 속성을 구분해야 하므로 설계와 구현의 복잡성 증가
- 상태를 분리하여 관리해야하기 때문에 자칫하면 코드 가독성이 떨어질 수 있음
실무에서 쓰이는 플라이웨이트 패턴
1. Integer.valueOf(int)
- 아래 주석에서 볼 수 있다시피 -128 ~ 127처럼 자주 쓰이는 정수에 대해서는 내부적으로 캐싱을 제공해 ==으로 비교해도 true 반환 (Primitive 타입이 아니기 때문에 원래는 equals로 비교해야 함)
- 실제로 Long.valueOf를 equals가 아닌 ==로 비교하여 장애 발생한 적이 있기 때문에 주의 필요

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void main(String[] args) { | |
Integer i1 = Integer.valueOf(10); | |
Integer i2 = Integer.valueOf(10); | |
System.out.println(i1 == i2); | |
i1 = Integer.valueOf(1000); | |
i2 = Integer.valueOf(1000); | |
System.out.println(i1 == i2); | |
} |

참고
코딩으로 학습하는 GoF의 디자인 패턴 - 백기선 강사님
반응형
'Design Pattern' 카테고리의 다른 글
[디자인 패턴] 책임 연쇄 패턴 (Chain-of-Responsibility Pattern) (0) | 2024.06.29 |
---|---|
[디자인 패턴] 프록시 패턴 (Proxy Pattern) (0) | 2024.06.29 |
[디자인 패턴] 퍼사드 패턴 (Facade Pattern) (0) | 2024.06.29 |
[디자인 패턴] 데코레이터 패턴 (Decorator Pattern) (0) | 2024.06.29 |
[디자인 패턴] 컴포짓 패턴 (Composite Pattern) (0) | 2024.06.22 |