设计模式之工厂方法模式
来源:互联网 发布:四连杆机构设计软件 编辑:程序博客网 时间:2024/05/17 07:38
上篇我们讲了简单工厂模式,也提到了简单工厂模式的缺点,这篇我们来讲一下工厂方法模式,而工厂方法模式在一定程度上避免了简单工厂模式的那些缺点,废话不多说,上代码咯。
工厂方法模式:
以下代码在VS2012上编译通过
#include <iostream>using namespace std;class Product{public: virtual void showProduct() {cout<<"showProduct"<<endl;}};class ProductA:public Product{public: void showProduct() { cout<<"showProductA"<<endl; }};class ProductB:public Product{public: void showProduct(){ cout<<"showProductB"<<endl; }};class Factory{public: virtual Product* createProduct() {return NULL;} };class FactoryA: public Factory{public: Product* createProduct() { return new ProductA(); }};class FactoryB:public Factory{public: Product* createProduct(){ return new ProductB(); }};int _tmain(int argc, _TCHAR* argv[]){ Factory* fa=new FactoryA();//创建生产A产品的工厂 Product* pa=fa->createProduct();//生产A产品 pa->showProduct();//显示A产品 Factory* fb=new FactoryB();//创建生产B产品的工厂 Product* pb=fb->createProduct();//生产B产品 pb->showProduct();//显示B产品 return 0;}
执行结果:
showProductA
showProductB
0 0
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式 之 工厂方法
- 设计模式 之 工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 《设计模式》之工厂方法
- 设计模式之--工厂方法
- SBT安装
- css+div学习笔记
- 插入排序 - InsertionSort
- UILabel顶端对齐
- UNIX命令学习--(解压和压缩命令)
- 设计模式之工厂方法模式
- GPIO实验 位操作
- TabHost简单使用示例
- 关于ArrayList的5道面试题
- Ubuntu LogViewer调试工具
- iTween
- Ubuntu14.04构建内核源码树的初级实践
- [实验-视频过程]RMAN备份和恢复
- 请求转发 和 重定向的区别