티스토리 뷰

여러 다른 객체를 조합해야 할 경우, 그 객체 들을 조립하는 코드가 중복이 될 여지가 있습니다. 여러 객체를 조합해 객체를 만드는 과정을 전담하는 클래스를 두는 것을 빌더 패턴이라고 부릅니다.



enum ITEM_OPTION_TYPE { ITEMOPTIONTYPE_NONE = -1, ITEMOPTIONTYPE_HEAL, ITEMOPTIONTYPE_POISON, }; class ItemOption { ITEM_OPTION_TYPE m_ItemOptionType; public: ItemOption(ITEM_OPTION_TYPE itemoptiontype){ m_ItemOptionType = itemoptiontype; } }; class ItemOptionHeal : public ItemOption { //체력회복기능 public: ItemOptionHeal(ITEM_OPTION_TYPE itemoptiontype) : ItemOption(itemoptiontype) { } bool LoadEffect(){ //힐기능사용시의이펙트를불러온다 return true; } }; class ItemOptionPoison : public ItemOption { //독기능 public: ItemOptionPoison(ITEM_OPTION_TYPE itemoptiontype) : ItemOption(itemoptiontype) { } bool LoadUseTargetSetting(){ //독기능의타겟설정을읽어온다 return true; } }; class ItemData { private: ItemOption *m_pItemOption; public: ItemData(){ m_pItemOption = 0; } void SetItemOption(ItemOption *itemoption){m_pItemOption = itemoption;} }; class ItemDataBuilder { protected: ItemData *m_pItemData; public: ItemData *CreateItemData(){ if(m_pItemData == NULL){ m_pItemData = new ItemData; } return m_pItemData; } virtual bool AddItemOption() { if(m_pItemData == NULL) return false; ItemOption *newItemOption = new ItemOption(ITEMOPTIONTYPE_NONE); m_pItemData->SetItemOption(newItemOption); return true; } }; class ItemDataHealBuilder : public ItemDataBuilder { virtual bool AddItemOption() //클래스에메소드를추가하는것이불가능할경우에는상속받은빌더클래스를만들고해당메소드를추가해주면된다. { if(m_pItemData == 0) return false; ItemOptionHeal *newItemOption = new ItemOptionHeal(ITEMOPTIONTYPE_HEAL); newItemOption->LoadEffect(); m_pItemData->SetItemOption(newItemOption); return true; } }; class ItemDataPoisonBuilder : public ItemDataBuilder { virtual bool AddItemOption() { if(m_pItemData == 0) return false; ItemOptionPoison *newItemOption = new ItemOptionPoison(ITEMOPTIONTYPE_POISON); newItemOption->LoadUseTargetSetting(); m_pItemData->SetItemOption(newItemOption); return true; } };


댓글