设计模式的工厂模式一共有三种:简单工厂模式,工厂模式,抽象工厂模式
简单工厂模式原理:只有一个工厂类,通过传参的形式确定所创建的产品对象种类
代码如下:
#include#include #include using namespace std;#define COREA 0#define COREB 1class Core{public: virtual void show(){}};class CoreA:public Core{public: virtual void show() { cout << "This is corea" < create(0); pcore->show(); return 0;}
工厂方法模式原理:通过在客户调用不同的工厂类来实现同一类对象的创建。
produce.h代码
#ifndef PRODUCE_H#define PRODUCE_H#includeusing namespace std;class Core{public: virtual void show(){}};class CoreA:public Core{public: virtual void show() { cout << "This is corea" <
factory.h代码
#ifndef FACOTRY_H#define FACOTRY_H#include#include "produce.h"using namespace std;class Factory{public: virtual Core* create(); };class FactoryCoreA:public Factory{ virtual Core* create();};class FactoryCoreB:public Factory{ virtual Core* create();};#endif
factory.cpp代码
#include#include "factory.h"using namespace std;Core* Factory::create(){ return NULL;}Core* FactoryCoreA::create(){ return new CoreA();}Core* FactoryCoreB::create(){ return new CoreB();}
客户main.cpp代码
#include#include #include #include "factory.h"#include "produce.h"using namespace std;#define COREA 0#define COREB 1int main(){ Factory * fa = new FactoryCoreA(); Core* pcore = fa->create(); pcore->show(); return 0;}
抽象工厂原理:抽象工厂可以创建一系列的产品,缺点如果是增加产品种类,需要重新修改抽象工厂接口和实现
部分代码如下
factory.cpp
#include#include "factory.h"#include "Board.h"using namespace std;Core* Factory::createcore(){ return NULL;}Core* FactorySeriaA::createcore(){ return new CoreA();}Core* FactorySeriaB::createcore(){ return new CoreB();}Board* Factory::createboard(){ return NULL;}Board* FactorySeriaA::createboard(){ return new BoardA();}Board* FactorySeriaB::createboard(){ return new BoardB();}
fatory.h
#ifndef FACOTRY_H#define FACOTRY_H#include#include "produce.h"#include "Board.h"using namespace std;class Factory{public: virtual Core* createcore(); virtual Board* createboard(); };class FactorySeriaA:public Factory{ virtual Core* createcore(); virtual Board* createboard();};class FactorySeriaB:public Factory{ virtual Core* createcore(); virtual Board* createboard();};#endif
新增的产品种类类Board.h
#ifndef BOARD_H#define BOARD_H#includeusing namespace std;class Board{public: virtual void show(){}};class BoardA:public Board{public: virtual void show() { cout << "This is boarda" <