factory工厂模式是所有模式中最有用的模式之一。它强制用一个factory工厂来创建对象,程序中所有需创建对象的代码都在这个factory中执行,它是Factory Method模式的变体。示例代码:
#include <iostream>
#include <stdexcept>
#include <cstddef>
#include <string>
#include <vector>
#include "../pruge.h"
using namespace std;
class Shape{
virtual void draw()=0;
virtual void erase()=0;
virtual ~Shape();
class BadShapeCreation:public logic_error{
public:
BadShapeCreation(string type):logic_error("Cann't create type"+typed){}
};
static Shape* factory(const string& type)
throw(BadShapeCreation);
};
class Circle:public Shape{
Circle(){};//private constructor
friend class Shape;
public:
void draw(){cout<<"Circle::draw"<<endl;}
void erase(){cout<<"Circle::erase"<<endl;}
~Circle(){cout<<"Circle::~Circle" <<endl;}
};
class Square:public Shape{
Square(){};//private constructor
friend class Shape;
public:
void draw(){cout<<"Square::draw"<<endl;}
void erase(){cout<<"Square::erase"<<endl;}
~Square(){cout<<"Square::~Circle" <<endl;}
};
Shape* Shape::factory(const string& type)
throw(Shape::BadShapeCreation){
if(type== "Circle") return new Circle;
if(type=="Square") return new Square;
throw BadShapeCreation(type);
}
char* sl[] = {"Circle","Square",Square","Circle","Circle","Circle",Square"};
int main(){
vector<Shape*> shape;
try{
for(size_t i = 0; i<sizeof(sl)/sizeof(sl[0]); ++i){
shape.push_back(shape::factory(sl[i]));
}catch(Shape::BadShpaeCreation e){
cout << e.what()<<endl;
purge(shapes);
return EXIT_FAILURE;
}
for(size_t i = 0; i < shapes.size(); i++){
shapes[i]->draw();
shapes[i]->erase();
}
pruge(shapes);
}
备注:factory()允许一个参数来决定何种类型的Shape对象,这里参数也可以是string。添加新的Shape类型时,只要修改factory()就可以。
为确保只能创建在factory()中,Shape把构造声明为私有,Shape有声明为友元(也可以把Shape::factory()声明为友元函数),这样factory()可以访问它的构造函数。这样做的缺点:一旦新类型被加入到这种结构来时,必须更新基类。