본문 바로가기
Theory/Design Pattern

Flyweight Pattern

by y.j 2022. 5. 9.
728x90

Flyweight Pattern

Flyweight Pattern은 미세하게 나누어진 매우 많은 object들을 효율적으로 공유하는 것이다.

미세하게 많은 양으로 나누어진 object를 어떻게 효율적으로 지원할까?
어떻게 많은 양의 object를 생성하는 것을 회피하면서 공유 할 수 있을까?
어떻게 object들을 물리적으로 적은 양으로 생성하면서 논리적으로 문제가 없게 object들을 표현할 수 있을까?

많은 object들을 다루기 위한 기본적인 방법은 필요한 만큼 object들을 생성하는 것이다. 이러한 방법은 많은 메모리를 차지하고 overhead를 일으킬 수 있다. 이것들을 해결하기 위해서는 물리적으로 생성되는 object의 수를 줄여야 하면서 논리적으로도 모든 객체가 존재해야만 한다.

 

solution

instrinsic state와 extrinsic state에 대한 개념이 먼저 필요하다. instrinsic state은 불변하고, extrinsic state는 변수이다. 이것을 활용하는 예를 들자면 text document에서 같은 명사라도 위치에 따라 주어 목적어 보어로 쓰일 수 있는데 intrinsic state가 word라면 extrinsic state는 word의 position이 된다.

Flyweight object는 extrinsic state를 가진다.

public class Flyweight1 implements Flyweight {
    private String intrinsicState;
    public Flyweight1(String intrinsicState) {
        this.intrinsicState = intrinsicState;
    }
    @Override
    public String operation(int extrinsicState) {
        return " performing an operation on the flyweight\n "
                + " with intrinsic state = " + intrinsicState
                + " and passed in extrinsic state = " + extrinsicState + ".";
    }
}

하지만 FlyweightFactory에서 key, Flyweight의 맵으로 가지고 있어 Flyweight에 대한 key는 유일하다.

public class FlyweightFactory {
    private static final FlyweightFactory INSTANCE = new FlyweightFactory();
    private FlyweightFactory() {}

    public static FlyweightFactory getInstance() {
        return INSTANCE;
    }

    private Map<String, Flyweight> flyweights = new HashMap<String, Flyweight>();

    public Flyweight getFlyweight(String key) {
        if(flyweights.containsKey(key)) {
            System.out.println("S h a r i n g     a flyweight with key = " + key);
            return flyweights.get(key);
        }
        else {
            System.out.println("C r e a t i n g    a flyweight with key = " + key);
            Flyweight flyweight = new Flyweight1(key);
            flyweights.put(key, flyweight);
            return flyweight;
        }
    }
    public int getSize() {
        return flyweights.size();
    }
}

같은 key로 찾으면 Flyweight는 같은 object이지만 extrinsic state를 통해 서로 구별 할수 있게 된다.

Advantages

• 적은 물리적 object만을 생성해서 논이적으로 서로 다른 객체들을 무수히 많이 표현할 수 있다.

Disadvantages

• run-time비용이 든다.

 - Client는 extrinsic state를 run-time에 유동적으로 통과해야 할 책임이 있어

   extrinsic state를 저장, 반환, 계산하는데 메모리를 사용해야하고 system performance에 영향을 끼칠 수 있다.
• object에 identity가 없다.

 - 같은 object지만 서로 다른 논리적인 object이므로

   반드시 하나의 객체가 identity를 가져야 하는 application에서는 유용하지 않다.

 

[전체코드]

https://github.com/jKyounju/adapterPatterns/tree/master/src/StructurePattern/FlyweightPattern

728x90

'Theory > Design Pattern' 카테고리의 다른 글

Command Pattern  (0) 2022.05.12
Chain Of Responsibility Pattern  (0) 2022.05.10
Facade Pattern  (0) 2022.05.09
Decorator Pattern  (0) 2022.05.08
Composite Pattern  (0) 2022.05.05

댓글