特性
|
简单工厂模式
|
工厂方法模式
|
抽象工厂模式
|
创建对象的职责
|
单一工厂类负责所有产品创建
|
子类决定创建具体对象
|
子类决定创建一系列相关对象
|
遵循开闭原则
|
不符合,增加新产品需修改工厂类
|
符合,增加新产品无需修改工厂类
|
部分符合,增加产品族符合
|
系统复杂性
|
较低
|
中等
|
较高
|
产品族一致性支持
|
不支持
|
不支持
|
支持
|
#include <iostream> #include <memory> #include <string> // 抽象产品类:咖啡 class Coffee { public: virtual ~Coffee() {} virtual std::string getDescription() const = 0; virtual double cost() const = 0; }; // 具体产品类:美式咖啡 class Americano : public Coffee { public: std::string getDescription() const override { return "Americano"; } double cost() const override { return 5.0; } }; // 抽象产品类:咖啡杯 class CoffeeCup { public: virtual ~CoffeeCup() {} virtual std::string getDescription() const = 0; }; // 具体产品类:美式咖啡杯 class AmericanoCup : public CoffeeCup { public: std::string getDescription() const override { return "Americano Cup"; } }; // 抽象产品类:咖啡勺 class CoffeeSpoon { public: virtual ~CoffeeSpoon() {} virtual std::string getDescription() const = 0; }; // 具体产品类:美式咖啡勺 class AmericanoSpoon : public CoffeeSpoon { public: std::string getDescription() const override { return "Americano Spoon"; } }; // 抽象工厂类 class CoffeeFactory { public: virtual ~CoffeeFactory() {} virtual std::shared_ptr<Coffee> createCoffee() const = 0; virtual std::shared_ptr<CoffeeCup> createCoffeeCup() const = 0; virtual std::shared_ptr<CoffeeSpoon> createCoffeeSpoon() const = 0; }; // 具体工厂类:美式咖啡工厂 class AmericanoFactory : public CoffeeFactory { public: std::shared_ptr<Coffee> createCoffee() const override { return std::make_shared<Americano>(); } std::shared_ptr<CoffeeCup> createCoffeeCup() const override { return std::make_shared<AmericanoCup>(); } std::shared_ptr<CoffeeSpoon> createCoffeeSpoon() const override { return std::make_shared<AmericanoSpoon>(); } }; int main() { // 创建美式咖啡及其配套杯子和勺子 std::shared_ptr<CoffeeFactory> americanoFactory = std::make_shared<AmericanoFactory>(); std::shared_ptr<Coffee> americano = americanoFactory->createCoffee(); std::shared_ptr<CoffeeCup> americanoCup = americanoFactory->createCoffeeCup(); std::shared_ptr<CoffeeSpoon> americanoSpoon = americanoFactory->createCoffeeSpoon(); std::cout << "Coffee: " << americano->getDescription() << ", Cost: " << americano->cost() << std::endl; std::cout << "Cup: " << americanoCup->getDescription() << std::endl; std::cout << "Spoon: " << americanoSpoon->getDescription() << std::endl; return 0; }