플라이웨이트 패턴이란?

 

Flyweight = 경량화하다.

 

쉬운 개념이다.

 

1) 어려운 설명

한개의 고유 상태를 다른 객체들에게 공유하게 만들어 메모리 사용량을 줄인다.

동일한 객체를 팩토리를 통해 map 구조로 관리하여 중복없이 사용한다.

 

2) 쉬운 설명

똑같은 내용을 메모리에 여러번 올릴 필요 없이 하나만 올리고 여러곳에서 가리키는 것

 

주로 게임 이미지 연출에서 많이 사용하는 듯 하다.

숲을 표현할때 숲에 나무가 100그루 있다면 메모리에 나무객체 100개를 올릴 필요 없이 하나의 나무객체를 만들고 만들어진 하나의 나무의 메모리를 100곳에서 가리키는 식으로 사용하면 된다.

 

또는 ott사이트같은 영상 컨텐츠를 보여주는 사이트에서 사용자가 컨텐츠를 요구할때마다 파일을 로딩하는 것이 아니라 메모리에 이미 로딩되어 있는지 체크한 후 로딩되어 있다면 해당 위치를 전해줌으로써 쓸데없이 메모리에 여러번 로딩하지 않고 하나만 로딩되게 만드는 패턴이다.

 

싱글톤의 구조패턴 버전(다만 싱글톤처럼 static을 사용하는것은 아니고 map을 사용)

 

 

 

플라이웨이트 패턴의 구조

 

Flyweight 클래스가 로딩될 영화객체

Flyweight Factory 클래스가 해당 영화가 로딩되어 있는지 확인하는 팩토리 객체

 

 

 

 

구현 코드 예시

 

1) Flyweight 클래스

로딩될 영화객체가 위치하는 클래스

class Movie {
private:
    string title;

public:
    Movie(string title) {
        this->title = title;
        cout << "Load " << title << '\n';
    }

    void play() {
        cout << "Play:" << title << endl;
    }
};

 

2) Flyweight Factory 클래스

맵에서 이미 로드되어 있는지 찾아보고 있으면 해당 위치 return, 없으면 로딩시키고 나서 return

class ContentsFactory {
private:
    map<string, Movie*> contentsList;

public:
    Movie* getContents(string key) {
        if (contentsList.find(key) == contentsList.end()) { // 없다면
            contentsList[key] = new Movie(key);
        }
        else { // 이미 로딩되어있다면
            cout << "reuse\n";
        }

        return contentsList[key];
    }
};

 

3) main 함수

int main() {
    ContentsFactory* contentsFactory = new ContentsFactory();

    Movie* movie1 = contentsFactory->getContents("Big short");
    movie1->play();

    Movie* movie2 = contentsFactory->getContents("Big short");
    movie2->play();

    return 0;
}

 

4) 실행결과

 

 

 

 

 

 

※ 참고 문헌

https://en.wikipedia.org/wiki/Flyweight_pattern

https://ansohxxn.github.io/design%20pattern/chapter8/

https://d-yong.tistory.com/48?category=700951