CS/디자인패턴
[디자인 패턴][구조 패턴] - 플라이웨이트 패턴
흰무
2023. 7. 13. 11:02
1. 플라이웨이트 패턴
객체 공유를 통해 메모리 사용을 최적화하는 패턴
다수의 유사한 객체를 생성하는 상황에서 중복된 데이터를 공유함으로써 메모리 사용을 줄이고 성능을 향상
동일한 내용을 가진 객체를 여러 개 생성할 필요 없이, 객체를 공유
- 사용하는 경우
- 많은 수의 유사한 객체를 생성해야 할 때
- 객체 생성 비용이 높고, 중복 데이터가 많이 포함된 경우
- 객체가 불변(Immutable)하거나, 상태가 외부에서 공유 가능한 경우
- 구현 방법
- Flyweight : 공유 가능한 객체를 정의하는 인터페이스 또는 추상 클래스, 내부 상태를 가지며, 외부에서 공유 가능한 상태를 가진 객체를 생성하는 메서드를 제공
- ConcreteFlyweight 클래스 : Flyweight 인터페이스를 구현하고 내부 상태를 저장하는 클래스, 객체를 공유하고, 중복 데이터를 공유 메커니즘을 통해 처리
- FlyweightFactory 클래스 : Flyweight 객체를 관리하고 반환하는 팩토리 클래스입니다. 객체의 생성과 공유를 제어
- 예제
import java.util.HashMap;
import java.util.Map;
// Flyweight 인터페이스
interface Shape {
void draw();
}
// ConcreteFlyweight 클래스
class Circle implements Shape {
private String color;
private int x;
private int y;
private int radius;
public Circle(String color) {
this.color = color;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setRadius(int radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing a circle with color: " + color +
", x: " + x + ", y: " + y + ", radius: " + radius);
}
}
// FlyweightFactory 클래스
class ShapeFactory {
private static final Map<String, Shape> circleMap = new HashMap<>();
public static Shape getCircle(String color) {
Circle circle = (Circle) circleMap.get(color);
if (circle == null) {
circle = new Circle(color);
circleMap.put(color, circle);
System.out.println("Creating a new circle of color: " + color);
}
return circle;
}
}
// 클라이언트 코드
public class Main {
private static final String[] colors = { "Red", "Green", "Blue" };
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Circle circle = (Circle) ShapeFactory.getCircle(getRandomColor());
circle.setX(getRandomX());
circle.setY(getRandomY());
circle.setRadius(10);
circle.draw();
}
}
private static String getRandomColor() {
return colors[(int) (Math.random() * colors.length)];
}
private static int getRandomX() {
return (int) (Math.random() * 100);
}
private static int getRandomY() {
return (int) (Math.random() * 100);
}
}
FlyWeightFactory 클래스에서 객체가 관리 되기 때문에, 동일한 색상의 도형이 여러번 그려져도, 실제로는 하나의 "Circle" 객체만이 생성되고 공유된다.