본문 바로가기

디자인 패턴

디자인 패턴 - 플라이웨이트 패턴(Flyweight Pattern)

1. 정의

  • 인스턴스 하나로 여러 개의 가상 인스턴스를 제공할 때 사용한다.

💡 인스턴스가 하나이기 때문에 모두 똑같은 방식으로 처리할 수 있다.

2. 예시

  • 조경 설계 애플리케이션에서 나무를 객체 형태로 추가한다. 단, 많이 추가해도 실행이 느려지지 않아야 한다.

3. 그림

4. 클래스 다이어그램

5. 코드

public class Client {
    public static void main(String[] args){

        TreeManager treeManager = new TreeManager();
        treeManager.displayTree();
    }
}
/* 출력
------
x좌표 : 1
y좌표 : 2
------
x좌표 : 2
y좌표 : 3
------
x좌표 : 3
y좌표 : 4
------
x좌표 : 5
y좌표 : 6
*/
public class Tree {
    int x, y;

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public void display(){
        System.out.println("------");
        System.out.println("x좌표 : " + x);
        System.out.println("y좌표 : " + y);
    }
}
public class TreeManager {
    int[][] treesCoordinate = new int[][]{
            new int[]{1, 2},
            new int[]{2, 3},
            new int[]{3, 4},
            new int[]{5, 6},
    };

    public void displayTree(){
        Tree tree = new Tree();
        for (int[] xy : treesCoordinate) {
            tree.setX(xy[0]);
            tree.setY(xy[1]);
            tree.display();
        }
    }
}

https://github.com/kang-seongbeom/design_pattern

💡 Github에서 디자인 패턴 코드를 볼 수 있습니다.

6. 설명

  • 나무의 모든 상태를 TreeManger가 이차원 배열 형태로 관리한다.
  • Tree인스턴스를 단 하나만 사용하고, 상태의 만 바꿔 처리를 한다.
  • 하나의 인스턴스만 사용하기 때문에, 모두 똑같이 처리할 수 밖에 없다는 장점이자 단점이 있다.