#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 Latte : public Coffee { public: std::string getDescription() const override { return "Latte"; } double cost() const override { return 6.0; } }; // 抽象工厂类 class CoffeeFactory { public: virtual ~CoffeeFactory() {} virtual std::shared_ptr<Coffee> createCoffee() const = 0; }; // 具体工厂类:美式咖啡工厂 class AmericanoFactory : public CoffeeFactory { public: std::shared_ptr<Coffee> createCoffee() const override { return std::make_shared<Americano>(); } }; // 具体工厂类:拿铁咖啡工厂 class LatteFactory : public CoffeeFactory { public: std::shared_ptr<Coffee> createCoffee() const override { return std::make_shared<Latte>(); } }; int main() { // 创建美式咖啡 std::shared_ptr<CoffeeFactory> americanoFactory = std::make_shared<AmericanoFactory>(); std::shared_ptr<Coffee> americano = americanoFactory->createCoffee(); std::cout << "Description: " << americano->getDescription() << ", Cost: " << americano->cost() << " RMB" << std::endl; // 创建拿铁咖啡 std::shared_ptr<CoffeeFactory> latteFactory = std::make_shared<LatteFactory>(); std::shared_ptr<Coffee> latte = latteFactory->createCoffee(); std::cout << "Description: " << latte->getDescription() << ", Cost: " << latte->cost() << " RMB" << std::endl; return 0; }