工廠模式(Factory)算是設計模式裡最好懂、也最好用的一個。它的目的只有一句話:根據不同的要求,交出不同的產品。
打個比方,一家鞋廠既做皮鞋,也做膠鞋。用代碼描述,先抽出一個共同的產品結構:
typedef struct _Shoe
{
int type;
void (*print_shoe)(struct _Shoe*);
}Shoe;
不同產品的差異,落在各自的行為函數上:
void print_leather_shoe(struct _Shoe* pShoe)
{
assert(NULL != pShoe);
printf("This is a leather shoe!\n");
}
void print_rubber_shoe(struct _Shoe* pShoe)
{
assert(NULL != pShoe);
printf("This is a rubber shoe!\n");
}
於是「工廠」只需根據入參決定裝配哪一條產線,做出來的東西對外觀看卻是同一副模樣:
#define LEATHER_TYPE 0x01
#define RUBBER_TYPE 0x02
Shoe* manufacture_new_shoe(int type)
{
assert(LEATHER_TYPE == type || RUBBER_TYPE == type);
Shoe* pShoe = (Shoe*)malloc(sizeof(Shoe));
assert(NULL != pShoe);
memset(pShoe, 0, sizeof(Shoe));
if(LEATHER_TYPE == type)
{
pShoe->type = LEATHER_TYPE;
pShoe->print_shoe = print_leather_shoe;
}
else
{
pShoe->type = RUBBER_TYPE;
pShoe->print_shoe = print_rubber_shoe;
}
return pShoe;
}
仔細對照會發現,流傳的版本裡有兩處寫成了 pShoe->type == LEATHER_TYPE;。這是典型的把賦值 = 誤寫成比較 ==:表達式求了值卻沒落到對象上,而且編譯器通常不會報錯,只給一條「語句無效」的警告。上面已經改正為賦值。這類錯誤在開啟較高警告等級時能被提前攔住,值得養成習慣。
工廠模式的價值在於把「創建」從「使用」中剝離出去:調用方只認得 Shoe 這個抽象,新增品類時改動集中在工廠一處,不必去翻遍所有業務代碼。缺點也同樣明顯——每加一種產品,工廠的分支就得再長一截,品類爆炸時需要引入抽象工廠或註冊表的方式來緩解。