#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: enum CoffeeType { AMERICANO, LATTE }; static std::shared_ptr<Coffee> createCoffee(CoffeeType type) { switch (type) { case AMERICANO: return std::make_shared<Americano>(); case LATTE: return std::make_shared<Latte>(); default: return nullptr; } } }; int main() { // 创建美式咖啡 std::shared_ptr<Coffee> americano = CoffeeFactory::createCoffee(CoffeeFactory::AMERICANO); std::cout << "Description: " << americano->getDescription() << ", Cost: " << americano->cost() << " RMB" << std::endl; // 创建拿铁咖啡 std::shared_ptr<Coffee> latte = CoffeeFactory::createCoffee(CoffeeFactory::LATTE); std::cout << "Description: " << latte->getDescription() << ", Cost: " << latte->cost() << " RMB" << std::endl; return 0; }