factory工廠模式是所有模式中最有用的模式之一。它強(qiáng)制用一個(gè)factory工廠來創(chuàng)建對象,程序中所有需創(chuàng)建對象的代碼都在這個(gè)factory中執(zhí)行,它是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()允許一個(gè)參數(shù)來決定何種類型的Shape對象,這里參數(shù)也可以是string。添加新的Shape類型時(shí),只要修改factory()就可以。
為確保只能創(chuàng)建在factory()中,Shape把構(gòu)造聲明為私有,Shape有聲明為友元(也可以把Shape::factory()聲明為友元函數(shù)),這樣factory()可以訪問它的構(gòu)造函數(shù)。這樣做的缺點(diǎn):一旦新類型被加入到這種結(jié)構(gòu)來時(shí),必須更新基類。