// // // // // // // // //
///2013.1.12
// // // // // // // // //
作为设计模式中较为简单的一个,
Factory本身的目的也比较单纯:
【核心】在工厂类中根据不同的客户需求产生出来不同的产品。
首先我们先来看一下此模式UML图:
如图所示,
Fatory Pattern 在C++中最主要的类是Factory,
在这个类中集合了生产Product类的方法(CreateProduct),
不过,
在这里有一个问题,
就是在Factory类中只是提供了一个接口,
并没有去实现。
于是,
他就需要一个子类,
也就是图中所示的ConcreteFactory类,
在这个类中,
实现了对具体Product类的创建。
就像是富士康,
它的工厂就是为了生产产品而存在,
但是具体生产iPod Touch Large还是生产iPhone 5S mini,
这个就要根据订单而定了,
然后再具体去执行。
顺便一提,
在Java中实现要更简单一点,
在Factory中添加一个返回IProduct类的接口就可以轻松实现。
当然C++也可以使用抽象类来实现。
如下为代码示例:
Product.h
#ifndef _PRODUCT_H_ #define _PRODUCT_H_ enum { iPhone5sMini, iPodTouchLarge }; class Product { public: Product(){} ~Product(){} }; class IPodTouchLarge: public Product { public: IPodTouchLarge(); }; class IPhone5sMini:public Product { public: IPhone5sMini(); }; #endif
Product.cpp
#include "Product.h" #include<iostream> IPodTouchLarge::IPodTouchLarge() { std::cout<<"Produce an iPodTouch Large"<<std::endl; } IPhone5sMini::IPhone5sMini() { std::cout<<"Produce an iPhone5s Mini"<<std::endl; }
Factory.h
#ifndef _FACTORY_H_ #define _FACTORY_H_ class Product; class Factory { public: virtual Product* create(int catalog)=0; protected: ~Factory(){} Factory(){} }; class FactoryCreator:public Factory { public: Product* create(int catalog); FactoryCreator(){} }; #endif
Factory.cpp
#include "Factory.h" #include "Product.h" Product* FactoryCreator::create(int catalog) { if(catalog == iPhone5sMini) return new IPhone5sMini(); else if(catalog == iPodTouchLarge) return new IPodTouchLarge(); return nullptr; }
main.cpp
#include"Factory.h" #include"Product.h" int main(int argc,char* argv[]) { Factory* fuShiKang = new FactoryCreator(); Product* product = fuShiKang->create(iPodTouchLarge); product = fuShiKang->create(iPhone5sMini); return 0; }
以及最后是输出结果: