一、簡單工廠
概述:
簡單工廠模式又稱爲靜態工廠方法(Static Factory Method)模式,屬於類的創建型模式,通常根據一個條件(參數)來返回不同的類的實例。他是用來專門生產對象的類。對象的創建由工廠類來負責,而不需要類使用者處理對象的創建。
UML圖:
優缺點:
優點:簡單工廠模式能夠根據外界給定的信息,決定究竟應該創建哪個具體類的對象。通過它,外界與具體類創建隔離開來,偶合性低。
缺點:工廠類集中了所有實例的創建邏輯。如果需要添加新的類,則就需要改變工廠類了,增加相應的類創建方法,這違反了開放-封閉原則。
應用情景:
工廠類負責創建的對象比較少時。
客戶只知道傳入了工廠類的參數,對於始何創建對象(邏輯)不關心。
代碼實現:
#include <cstdio>
#include <map>
#include <string>
//產品基類
class IProduct
{
public:
IProduct(){}
virtual ~IProduct(){}
};
//具體產品
class CProductA : public IProduct
{
public:
CProductA(){}
virtual ~CProductA(){}
};
class CFactory
{
public:
CFactory(){}
~CFactory(){Destory();}
//工廠單例
static CFactory* GetIntance()
{
printf("1、獲取工廠單例!\n");
static CFactory factory;
return &factory;
}
//生產產品
IProduct* Create(const std::string& name)
{
printf("2、生產產品!\n");
//是否已存在該產品
if (m_mProduct.end() != m_mProduct.find(name))
return m_mProduct.find(name)->second;
//生產新產品
IProduct* pProduct = NULL;
if (!strcmp("CProductA", name.c_str()))
pProduct = new CProductA();
else
return NULL;
m_mProduct.insert(std::pair<std::string, IProduct*>(name, pProduct));
return pProduct;
}
private:
//內存回收,銷燬所有產品
void Destory()
{
printf("4、銷燬所有產品!\n");
M_PRODUCT::iterator iter, it_end=m_mProduct.end();
for (iter=m_mProduct.begin(); iter!=it_end; ++iter)
{
delete iter->second;
iter->second = NULL;
}
}
private:
typedef std::map<std::string, IProduct*> M_PRODUCT;
M_PRODUCT m_mProduct;
};
int main(int argc, char **argv)
{
//調用工廠,生產產品
IProduct* pProductA = CFactory::GetIntance()->Create("CProductA");
//
printf("3、產品應用!\n");
return 0;
}
綜述:
簡單工廠模式不能說是一個設計模式,說它是一種編程習慣可能更恰當些。因爲它至少不是Gof23種設計模式之一。但它在實際的編程中經常被用到,而且思想也非常簡單,可以說是工廠方法模式的一個引導,
另:個人覺得,自已寫的這份代碼考慮的應該比較全面了,可以實際項目中應用。