工廠模式不允許將創(chuàng)建對(duì)象的代碼散布于整個(gè)系統(tǒng)。如果程序中所有需要?jiǎng)?chuàng)建對(duì)象的代碼都轉(zhuǎn)到這個(gè)工廠執(zhí)行,那么在增加新對(duì)象時(shí)所要做的全部工作就是只需修改工廠。這種設(shè)計(jì)時(shí)眾所周知
的工廠方法模式的一種變體。由于每個(gè)面向?qū)ο髴?yīng)用程序都需要?jiǎng)?chuàng)建對(duì)象,并且由于人們可能通過(guò)添加新類型來(lái)擴(kuò)展應(yīng)用程序,工廠模式可能是所有設(shè)計(jì)模式中最有用的模式之一。實(shí)現(xiàn)工廠模式的一種方法就是在基類中定義一個(gè)靜態(tài)成員函數(shù),示例如下:
#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();
}
}
函數(shù)factory 允許以一個(gè)參數(shù)來(lái)決定創(chuàng)建何種類型的Shape。在這里,參數(shù)類型為string,也可以是任何數(shù)據(jù)集。為了確保對(duì)象的創(chuàng)建只能發(fā)生在函數(shù)factory()中,Shape的特定類型的構(gòu)造函數(shù)被設(shè)為私有,同時(shí)Shape被聲明為友元類,因此factory()能夠訪問(wèn)這些構(gòu)造函數(shù)。
參考: C++編程思想卷2