工廠模式不允許將創建對象的代碼散布于整個系統。如果程序中所有需要創建對象的代碼都轉到這個工廠執行,那么在增加新對象時所要做的全部工作就是只需修改工廠。這種設計時眾所周知
的工廠方法模式的一種變體。由于每個面向對象應用程序都需要創建對象,并且由于人們可能通過添加新類型來擴展應用程序,工廠模式可能是所有設計模式中最有用的模式之一。實現工廠模式的一種方法就是在基類中定義一個靜態成員函數,示例如下:
#include<iostream>
#include<stdexcept>
#include<cstddef>
#include<string>
#include<vector>
using namespace std;
class Shape
{
public:
virtual void draw()=0;
virtual void erase()=0;
virtual ~Shape(){}
class BadShapeCreation :public logic_error
{
public:
BadShapeCreation(string type):
logic_error("Cannot create type"+type){}
};
static Shape* factory(const string &type)
throw(BadShapeCreation);
};
class Circle:public Shape
{
Circle(){}
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(){}
friend class Shape;
public:
void draw(){cout<<"Square::draw"<<endl;}
void erase(){cout<<"Square::erase"<<endl;}
~Square(){cout<<"Square::~Square"<<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*>shapes;
try{
for(size_t i=0;i<sizeof sl/sizeof sl[0];i++)
shapes.push_back(Shape::factory(sl[i]));
}catch(Shape::BadShapeCreation e)
{
cout<<e.what()<<endl;
return -1;
}
for(size_t i=0;i<shapes.size();i++)
{
shapes[i]->draw();
shapes[i]->erase();
}
}
函數factory 允許以一個參數來決定創建何種類型的Shape。在這里,參數類型為string,也可以是任何數據集。為了確保對象的創建只能發生在函數factory()中,Shape的特定類型的構造函數被設為私有,同時Shape被聲明為友元類,因此factory()能夠訪問這些構造函數。
參考: C++編程思想卷2