-
구조적(Structural) - 플라이웨이트(Flyweight) 패턴Java/디자인패턴 2024. 11. 15. 10:32반응형
플라이웨이트(Flyweight) 패턴은 구조적(Structural) 디자인 패턴의 하나로, 메모리 사용량을 줄이기 위해 객체의 공유를 활용하는 패턴입니다. 이 패턴은 많은 수의 객체가 동일하거나 유사한 속성을 가질 때, 중복 데이터를 줄여 메모리를 절약하는 데 유용합니다.
Flyweight 패턴의 핵심 개념
- 공유 가능한 상태(Intrinsic State): 객체 간에 공유할 수 있는 상태로, 객체가 공통적으로 가지는 속성입니다. 이러한 상태는 메모리 내에서 한 번만 저장됩니다.
- 비공유 상태(Extrinsic State): 객체별로 개별적인 상태로, 각 객체가 고유하게 가지는 속성입니다. 이 상태는 Flyweight 객체에서 분리하여 필요할 때마다 외부에서 제공됩니다.
- 사용 사례:
- 그래픽 시스템: GUI에서 동일한 아이콘이나 글자 모양 등을 반복해서 사용할 때, 각 객체를 개별적으로 생성하지 않고 공유하여 메모리 사용을 줄입니다.
- 게임 개발: 게임 캐릭터나 오브젝트들이 반복적으로 등장할 때, 중복되는 부분을 공유하여 성능을 개선합니다.
- 문서 편집기: 문서의 글자나 스타일을 저장할 때 같은 글자는 공유하여 메모리를 절약합니다.
Flyweight 패턴의 Java 예시
1. Flyweight 인터페이스 정의
interface Shape { void draw(String color); }
2. ConcreteFlyweight 클래스
class Circle implements Shape { private final String shapeType; // 공통 속성 private int radius; // 개별 속성 public Circle() { this.shapeType = "Circle"; this.radius = 5; // 기본 반지름 } @Override public void draw(String color) { System.out.println("Drawing a " + shapeType + " with color " + color + " and radius " + radius); } }
3. FlyweightFactory 클래스
import java.util.HashMap; import java.util.Map; class ShapeFactory { private static final Map<String, Shape> shapes = new HashMap<>(); public static Shape getCircle() { Shape circle = shapes.get("circle"); if (circle == null) { circle = new Circle(); shapes.put("circle", circle); System.out.println("Creating new Circle object."); } return circle; } }
4. Main 클래스 (실행 예시)
public class FlyweightPatternDemo { public static void main(String[] args) { Shape redCircle = ShapeFactory.getCircle(); redCircle.draw("Red"); Shape blueCircle = ShapeFactory.getCircle(); blueCircle.draw("Blue"); Shape greenCircle = ShapeFactory.getCircle(); greenCircle.draw("Green"); } }
결과 출력
Creating new Circle object. Drawing a Circle with color Red and radius 5 Drawing a Circle with color Blue and radius 5 Drawing a Circle with color Green and radius 5
코드 설명
- Shape 인터페이스는 draw 메서드를 정의하여 각 도형이 색상을 그릴 수 있도록 합니다.
- Circle 클래스는 Shape 인터페이스를 구현하며, shapeType과 같은 공통 속성을 가지고 있습니다.
- ShapeFactory는 FlyweightFactory 역할을 하며, 객체 풀(pool)에서 Circle 객체를 재사용합니다. getCircle() 메서드는 Circle 객체를 처음 생성할 때만 만들어주고 이후에는 공유된 객체를 반환합니다.
- FlyweightPatternDemo 클래스는 색상을 다르게 하여 동일한 Circle 객체를 재사용해 메모리 사용을 줄입니다.
Flyweight 패턴을 통해 객체가 공유됨으로써 메모리 절약 효과를 얻을 수 있으며, 객체 생성에 따른 비용을 줄일 수 있습니다. 대규모 객체가 필요할 때, 특히 속성이 반복되는 경우 이 패턴을 사용하면 시스템 성능이 개선됩니다.
반응형'Java > 디자인패턴' 카테고리의 다른 글
행동(Behavioral) - 중재자(Mediator) 패턴 (0) 2024.11.17 생성(Creational) - 추상 팩토리(Abstract Factory) 패턴 (0) 2024.11.16 행동(Behavioral) - 관찰자(Observer) 패턴 (0) 2024.11.14 구조패턴 - 프록시(Proxy) 패턴 (0) 2024.11.13 생성패턴 - 팩토리 메소드(Factory Method) 패턴 (0) 2024.11.12