Flyweight_Pattern - 8BitsCoding/RobotMentor GitHub Wiki

μ •μ˜

데이터λ₯Ό 곡유 μ‚¬μš©ν•˜μ—¬ λ©”λͺ¨λ¦¬λ₯Ό μ ˆμ•½ν•  수 μžˆλŠ” νŒ¨ν„΄

일반적으둜 κ³΅ν†΅μœΌλ‘œ μ‚¬μš©λ˜λŠ” κ°μ²΄λŠ” μƒˆλ‘œ μƒμ„±ν•˜μ—¬ μ‚¬μš©ν•˜μ§€ μ•Šκ³  곡유λ₯Ό 톡해 효율적으둜 μžμ›μ„ ν™œμš©ν•œλ‹€.

ν•œλ²ˆ μƒμ„±λœ κ°μ²΄λŠ” 두 번 μƒμ„±λ˜μ§€ μ•Šκ³ , 풀에 μ˜ν•΄μ„œ 관리 및 μ‚¬μš©λœλ‹€.

μ‹€μ œλ‘œ κ°€μž₯ 많이 μ‚¬μš©λ˜λŠ” νŒ¨ν„΄ 쀑에 ν•˜λ‚˜μ΄λ‹€.


μ˜ˆμ‹œλ‘œ μ„€λͺ…

이미지1

int main() {
    Item* potion = ItemFactory::GetInstance()->GetItem<Potion>(1);
    Item* axe = ItemFactory::GetInstance()->GetItem<Axe>(2);
    Item* map = ItemFactory::GetInstance()->GetItem<Map>(3);

    potion->operation();
    axe->operation();
    map->operation();


    // 예λ₯Ό λ“€μ–΄ μ΄λ ‡κ²Œ μ“°κ³  싢은 κ²ƒμž„.
    Item* map2 = ItemFactory::GetInstance()->GetItem<Map>(3);
    map2->operation();

    // μƒˆλ‘œμš΄ 맡을 생성해도 λ©”λͺ¨λ¦¬λ₯Ό μƒˆλ‘œ ν• λ‹Ήν•˜μ§€ μ•Šλ„λ‘.
}
class Item {
public:
    virtual void operation() = 0;
};

class Potion : public Item {
public:
    void operation() override { cout << "potion" << endl; }
};

class Axe : public Item {
public:
    void operation() override { cout << "Axe" << endl; }
};

class Map : public Item {
public:
    void operation() override { cout << "Map" << endl; }
};
template<typename T>
class Singleton {
protected:
    Singleton() {}
    vitual ~Singleton() {}
    Singleton(const Singleton& s) {}

private:
    static void destroy() {delete m_pInstance;}

public:
    static T* GetInstance() {
        if(m_pInstance == NULL) {
            m_pInstance = new T();
            atexit(destroy);
        }
        return m_pInstance;
    }

private:
    static T* m_Instance;
};
class ItemFactory : public Singleton<ItemFactory>
{
public:
    ~ItemFactory() {  }
 
public:
    template<typename T>
    Item* GetItem(int key)
    {
        if (mList.find(key) == mList.end())
        {
            mList[key] = new T;
        }
 
        return mList[key];
    }
 
private:
    map<int, Item*> mList;
};

μ°Έκ³ μ‚¬μ΄νŠΈ

μ°Έκ³ μ‚¬μ΄νŠΈ

⚠️ **GitHub.com Fallback** ⚠️