介紹
相較於簡單工廠模式,工廠方法模式將工廠端抽象化,讓實作該工廠的子工廠處理要創建的產品。可想像為原工廠的產線可生產玩具、文具、廚具,工廠方法模式將該工廠產線依產品種類獨立拉出來,A產線只產玩具,B產線只產文具,C產線只產廚具。
C++範例
#include <iostream>
class Monster
{
public:
virtual void Say() const = 0;
virtual ~Monster() {}
};
// 實作怪物介面1
class HeadcrabMonster : public Monster
{
public:
void Say() const override
{
std::cout << "I am a headcrab!" << std::endl;
}
};
// 實作怪物介面2
class ZombieMonster : public Monster
{
public:
void Say() const override
{
std::cout << "I am a zombie!" << std::endl;
}
};
// 現在工廠變成介面
class MonsterFactory
{
public:
virtual Monster *CreateMonster() = 0;
virtual ~MonsterFactory() {}
};
// 專產怪物1的工廠
class HeadcrabFactory : public MonsterFactory
{
public:
Monster *CreateMonster()
{
return new HeadcrabMonster();
}
};
// 專產怪物2的工廠
class ZombieFactory : public MonsterFactory
{
public:
Monster *CreateMonster()
{
return new ZombieMonster();
}
};
int main()
{
// 建立專產怪物A的工廠
HeadcrabFactory *headcrabFactory = new HeadcrabFactory();
// 用工廠創建怪物A
Monster *headcrab = headcrabFactory->CreateMonster();
headcrab->Say();
delete headcrab;
delete headcrabFactory;
// 建立專產怪物B的工廠
ZombieFactory *zombieFactory = new ZombieFactory();
// 用工廠創建怪物B
Monster *zombie = zombieFactory->CreateMonster();
zombie->Say();
delete zombie;
delete zombieFactory;
return 0;
}
Output:
I am a headcrab!
I am a zombie!