主页 > 软件开发  > 

8.工厂方法模式

8.工厂方法模式
一 典型工厂方法模式(Factory Method)结构图

二 典型工厂模式实现

测试代码 #include <iostream> using namespace std; class Product{ public: string name; virtual void show(){ cout << "我是:"; } }; class Desk : public Product { public: Desk(){ name = "桌子"; } void show(){ Product::show(); cout << name << endl; } }; class Cup : public Product { public: Cup(){ name = "杯子"; } void show(){ Product::show(); cout << name << endl; } }; class IFactory{ public: virtual Product* createProduct() = 0; }; class DeskFactory : public IFactory{ public: Product* createProduct(){ return new Desk(); } }; class CupFactory : public IFactory{ public: Product* createProduct(){ return new Cup(); } }; int main() { IFactory *ifactory = new DeskFactory(); Product *product = ifactory->createProduct(); product->show(); IFactory *ifactory_2 = new CupFactory(); Product *product_2 = ifactory_2->createProduct(); product_2->show(); return 0; }

测试结果:

我是:桌子 我是:杯子

参考: lkmao.blog.csdn.net/article/details/128952843

标签:

8.工厂方法模式由讯客互联软件开发栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“8.工厂方法模式