Flyweight_Pattern - 8BitsCoding/RobotMentor GitHub Wiki
λ°μ΄ν°λ₯Ό 곡μ μ¬μ©νμ¬ λ©λͺ¨λ¦¬λ₯Ό μ μ½ν μ μλ ν¨ν΄
μΌλ°μ μΌλ‘ 곡ν΅μΌλ‘ μ¬μ©λλ κ°μ²΄λ μλ‘ μμ±νμ¬ μ¬μ©νμ§ μκ³ κ³΅μ λ₯Ό ν΅ν΄ ν¨μ¨μ μΌλ‘ μμμ νμ©νλ€.
νλ² μμ±λ κ°μ²΄λ λ λ² μμ±λμ§ μκ³ , νμ μν΄μ κ΄λ¦¬ λ° μ¬μ©λλ€.
μ€μ λ‘ κ°μ₯ λ§μ΄ μ¬μ©λλ ν¨ν΄ μ€μ νλμ΄λ€.

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;
};