介紹
定義一個流程或算法的架構,其細節則在子類中實作。
C++範例
#include <iostream>
#include <memory>
// 抽象漢堡類
class Burger
{
public:
void Make()
{
// 製作漢堡都固定要加麵包、起司、肉片
AddBread();
AddCheese();
AddMeat();
}
virtual ~Burger() = default;
protected:
// 麵包、肉片的細節給子類去實作
virtual void AddBread() = 0;
virtual void AddMeat() = 0;
private:
// 假設每個漢堡使用的起司都是相同的
void AddCheese()
{
std::cout << "Burger adds normal cheese" << std::endl;
}
};
class PorkBurger : public Burger
{
protected:
// 豬肉漢堡的麵包、肉片細節
void AddBread() override
{
std::cout << "PorkBurger adds white bread" << std::endl;
}
void AddMeat() override
{
std::cout << "PorkBurger adds pork" << std::endl;
}
};
class BeefBurger : public Burger
{
protected:
// 牛肉漢堡的麵包、肉片細節
void AddBread() override
{
std::cout << "BeefBurger adds white bread" << std::endl;
}
void AddMeat() override
{
std::cout << "BeefBurger adds beef" << std::endl;
}
};
int main()
{
// 漢堡的製作流程是相同的,差別在於使用材料的區別
std::unique_ptr<Burger> porkBurger = std::make_unique<PorkBurger>();
porkBurger->Make();
std::cout << std::endl;
std::unique_ptr<Burger> beefBurger = std::make_unique<BeefBurger>();
beefBurger->Make();
return 0;
}
Output:
PorkBurger adds white bread
Burger adds normal cheese
PorkBurger adds pork
BeefBurger adds white bread
Burger adds normal cheese
BeefBurger adds beef