设计模式(3)-工厂模式
工厂模式是什么?
工厂模式又称为虚拟构造子模式或多态工厂模式,是在简单工厂模式的基础上,将核心角色“工厂类”改为层次继承结构,提取出一个抽象工厂的角色,由对应具体产品的具体工厂类来继承此抽象工厂,并提供抽象工厂的多态性,对外提供统一的产品创建接口。
工厂模式示意图如下所示。可以看出,创建产品的职责不再和简单工厂模式那样,集中在单个工厂类,而是分散到各具体工厂类,这样,既继承了简单工厂模式的优点:由工厂类承担创建产品的责任,客户类只需“消费”产品;又避免了其单个工厂类责任过于集中,新增产品需修改工厂类源代码的缺点。
工厂模式示例:水果农场
#include <iostream> #include <string> #include <algorithm>
class Fruit { public: virtual void grow() = 0; virtual void plant() = 0; virtual void harvest() = 0; };
class Apple : public Fruit { public: void grow() override { std::cout << "grow apple" << std::endl; } void plant() override { std::cout << "plant apple" << std::endl; } void harvest() override { std::cout << "harvest apple" << std::endl; } void SetTreeAge(uint32_t treeAge) { treeAge_ = treeAge; } uint32_t GetTreeAge() const { return treeAge_; }
private: uint32_t treeAge_ = 0; };
class Grape : public Fruit { public: void grow() override { std::cout << "grow grape" << std::endl; } void plant() override { std::cout << "plant grape" << std::endl; } void harvest() override { std::cout << "harvest grape" << std::endl; } void SetSeedless(bool seedless) { seedless_ = seedless; } bool IsSeedledd() const { return seedless_; }
private: bool seedless_ = false; };
class FruitGardener { public: virtual Fruit *Factory() = 0; };
class AppleGardener: public FruitGardener { public: Fruit * Factory() override { return new Apple(); } };
class GrapeGardener: public FruitGardener { public: Fruit * Factory() override { return new Grape(); } };
int main() { std::cout << "=== create apple ===" << std::endl; FruitGardener *appleGardener = new AppleGardener(); auto *apple = appleGardener->Factory(); apple->grow(); apple->harvest(); apple->plant();
std::cout << "=== create grape ===" << std::endl; FruitGardener *grapeGardener = new GrapeGardener(); auto *grape = grapeGardener->Factory(); grape->grow(); grape->harvest(); grape->plant();
delete apple; delete grape; delete appleGardener; delete grapeGardener; }
|
参考
《Java与模式》第13章