프로그래밍/GoF

[구조 패턴] - 플라이웨이트(Flyweight)

MAKGA 2022. 1. 12. 00:26
320x100

구조

#pragma once

#include <iostream>
#include <map>

class IFlyweight
{
public:
    virtual void Operation() = 0;
};

class Flyweight : public IFlyweight
{
public:
    void Operation() override
    {
        std::cout << "Operating Flyweight" << std::endl;
    }
};

class FlyweightFactory
{
public:
    FlyweightFactory()
    {
    }

    IFlyweight* GetFlyweight(std::string key)
    {
        IFlyweight* flyweight = nullptr;

        auto iter = flyweights_.find(key);
        if (iter == flyweights_.end())
        {
            flyweight = new Flyweight();
            flyweights_.insert(std::make_pair(key, flyweight));
        }

        return flyweight;
    }

private:
    std::map<std::string, IFlyweight*> flyweights_;
};

 

사용

int main()
{
    FlyweightFactory* flyweightFactory = new FlyweightFactory();

    std::vector<IFlyweight*> flyweights = 
    {
        flyweightFactory->GetFlyweight("A"),
        flyweightFactory->GetFlyweight("A"),
        flyweightFactory->GetFlyweight("B"),
        flyweightFactory->GetFlyweight("C"),
        flyweightFactory->GetFlyweight("C")
    };

    for(IFlyweight* flyweight : flyweights)
    {
        flyweight->Operation();
    }

    return 0;
}

경량 (Flyweight) 패턴은 마인크래프트의 블럭과 같이 중복되는 객체의 생성을 최소한으로 줄이고, 이미 생성된 객체를 가져와 얕은 복사를 수행한다. 그러면, 최소한의 메모리의 할당으로 클라이언트는 여럿이 참조된 객체의 고유 정보에 접근하여 정보를 얻어낼 수 있게 된다. 하지만, 경량화된 객체의 모든 정보는 공유되기에 상태 정보를 넣을 수가 없는데, 이는 상태 정보를 외부에서 가져와 처리할 수 있게 하는 방문자 (Visitor) 패턴을 응용할 수 있다.

 

320x100