工厂模式
#include <iostream> #include <memory> class Product { public: virtual void show() const { std::cout << "In Product show()." << std::endl; } }; class ConcreteProduct1 : public Product { public: void show() const override { std::cout << "In ConcreteProduct1 show()." << std::endl; } }; class ConcreteProduct2 : public Product { public: void show() const override { std::cout << "In ConcreteProduct2 show()." << std::endl; } }; class AbstractFactory { public: virtual std::unique_ptr<Product> createProduct() = 0; }; class ConcrateFactory1 : public AbstractFactory { public: std::unique_ptr<Product> createProduct() override { return std::make_unique<ConcreteProduct1>(); } }; class ConcrateFactory2 : public AbstractFactory { public: std::unique_ptr<Product> createProduct() override { return std::make_unique<ConcreteProduct2>(); } }; int main(int argc, char *argv[]) { std::unique_ptr<AbstractFactory> f = std::make_unique<ConcrateFactory1>(); std::unique_ptr<Product> p = f->createProduct(); p->show(); f = std::make_unique<ConcrateFactory2>(); p = f->createProduct(); p->show(); return 1; }