정리/Design Pattern

Flyweight Pattern - 플라이웨이트 패턴

javaju 2022. 3. 31. 20:36

이펙티브 자바를 공부하면서 플라이웨이트 패턴이 나와 개념 정리 및 실습을 해보려고 한다.

 

1. 플라이웨이트 패턴(Flyweight Pattern)이란?


동일하거나 유사한 객체들 사이에 가능한 많은 데이터를 서로 공유하여 사용하도록 하여 메모리 사용량을 최소화하는 디자인 패턴이다.

즉, 자주 변하는 속성과 변하지 않는 속성을 분리하고, 변하지 않는 속성은 재사용하여 메모리 사용을 줄이는 방식이다.

 

 

2. Flyweight Pattern의 구성


  • Flyweight : 공유에 사용할 클래스
  • FlyweightFactory : Flyweight 인스턴스를 생성 또는 공유
  • Client : Flyweight : 해당 패턴의 사용자

 

3. 실습


  • Shape (공유에 사용할 클래스들의 인터페이스)
public interface Shape {
	public void draw();
}

 

  • Circle (인터페이스 내용 및 필요한 속성 정의)
public 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 setColor(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("Circle [color= " + color +" , x= "+ x + " , y= "+ y +" , radius= "+ radius + " ]" );
	}
}

 

  • ShapeFactory (객체의 생성 또는 공유의 역할)
import java.util.HashMap;

public class ShapeFactory {
	public static final HashMap<String, Circle> circleMap = new HashMap<>();
	
	public static Shape getCircle(String color) {
		Circle circle = circleMap.get(color);
		
		if(circle == null) {
			circle = new Circle(color);
			circleMap.put(color, circle);
			System.out.println("---- 새로운 객체 생성 " + color +"색 원 ----" );
		}
		return circle;
	}
}

 

  • Main 클래스
public class Main {

	public static void main(String[] args) {
		String[] colors = {"Red", "Yellow", "Pink", "Blue"};
		
		for(int i=0;i<10;i++) {
			Circle circle = (Circle) ShapeFactory.getCircle(colors[(int) (Math.random()*4)]);
			circle.setX((int) (Math.random()*10));
			circle.setY((int) (Math.random()*20));
			circle.setRadius((int) (Math.random()*10));
			circle.draw();
		}
	}
}

 

  • 실행결과
---- 새로운 객체 생성 Blue색  ----
Circle [color= Blue , x= 8 , y= 5 , radius= 0 ]
---- 새로운 객체 생성 Red색  ----
Circle [color= Red , x= 5 , y= 5 , radius= 5 ]
---- 새로운 객체 생성 Pink색  ----
Circle [color= Pink , x= 6 , y= 17 , radius= 4 ]
Circle [color= Blue , x= 0 , y= 1 , radius= 6 ]
---- 새로운 객체 생성 Yellow색  ----
Circle [color= Yellow , x= 7 , y= 1 , radius= 4 ]
Circle [color= Yellow , x= 1 , y= 2 , radius= 0 ]
Circle [color= Red , x= 0 , y= 13 , radius= 3 ]
Circle [color= Yellow , x= 9 , y= 5 , radius= 1 ]
Circle [color= Pink , x= 1 , y= 16 , radius= 0 ]
Circle [color= Red , x= 7 , y= 11 , radius= 2 ]

같은 색상의 원은 1개만 생성되며, 생성된 객체를 공유하는 것을 확인할 수 있다.

 

 

4. 결론


4.1 언제 플라이웨이트 패턴을 사용하면 좋을까?

  • 공통적인 인스턴스를 많이 생성하는 로직이 포함된 경우
  • 자주 변하지 않는 속성을 재사용하는 경우

 

4.2 싱클톤 패턴과의 차이는 뭘까?

  • 싱클톤 패턴은 클래스 자체가 오직 1개의 인스턴스만 허용
  • 플라이웨이트 패턴은 싱글톤이 아닌 클래스 팩토리에서 제어

--> 인스턴스 생성의 제한을 어디서 제어하느냐의 차이

 

4.3 어디에서 플라이웨이트 패턴을 사용할까?

  • 임베디드와 같이 메모리를 최소한으로 사용해야 하는 경우에 활용
  • 클래스의 객체를 많이 만들어야할 때 사용

 

 

 

## 참고한 블로그 ##

 

[디자인패턴/Design Pattern] Flyweight Pattern / 플라이웨이트 패턴

관련 내용은 [자바 언어로 배우는 디자인 패턴 입문] , [Head First Design Pattern] 의 내용을 참고해서 정리한 글입니다. 잘못된 부분은 댓글로 피드백 부탁드립니다. 1. Flyweight 패턴이란? 어떤 클래스

lee1535.tistory.com

 

[구조 패턴] 플라이웨이트 패턴

1. 플라이웨이트 패턴(Flyweight Pattern)이란? 객체를 가볍게 만들어 메모리 사용을 줄이는 패턴 공통으로 사용하는 클래스(Flyweight)를 생성하는 팩토리 클래스(FlyweightFactory)를 만들어, 인스턴스를 최

dev-youngjun.tistory.com