Design Patterns/Structural Patterns

Flyweight Pattern (C++)

개발새발 2019. 11. 9. 18:33
반응형

Flyweight Pattern (플라이웨이트 패턴)

목적

동일한 객체를 관리하고 공유하여 메모리를 절약한다. 객체관리는 팩토리를 통해서 하며 객체들을 중복없이 관리하기 위해 map자료구조를 활용한다.

 

 

사용 시나리오

  • 어떤 플렛폼에서 광고용 영상 컨텐츠를 관리한다고 가정한다.
  • 사용자가 컨텐츠를 요구할 때 파일을 한번만 로딩한 뒤 다음 사용자 부터는 로딩하지 않고 컨텐츠를 제공한다.

[Flyweight]

 

class Contents {
public:
    virtual void play() = 0;
};

[ConcreteFlyweight]

 

class Movie : public Contents {
public:
    Movie(string title) {
        this->title = title;
        cout<<"Load "<<title<<endl;
    }
    virtual void play() override final {
        cout<<"Play:" <<title<<endl;
    }
private:
    string title;
};

[FlyweightFactory]

 

class ContentsFactory {
public:
    Contents* getContents(string key) {
        if(contentsList.find(key) == contentsList.end()) {
            contentsList[key] = new Movie(key);
        } else {
            cout<<"reuese"<<endl;
        }
        
        return contentsList[key];
    }
private:
    map<string, Contents*> contentsList;
};

[Client]

int main(int argc, const char * argv[]) {
    ContentsFactory* contentsFactory = new ContentsFactory();
    
    Contents* movie = contentsFactory->getContents("Big short");
    movie->play();
    
    Contents* movie2 = contentsFactory->getContents("Big short");
    movie2->play();
    
    return 0;
}

 

실행결과

Load Big short

Play:Big short

reuese

Play:Big short

반응형