factory工厂模式实际上polymorphic factory多态工厂的特例。
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <stdexcept>
#include <cstddef>
#include "../purge.h"
using namespace std;
class Shape{
public:
virtual void draw()=0;
virtual void erase()=0;
virtual ~Shape();
};
class ShapeFactory{
virtual Shape* create()=0;//不能直接调用,可以覆盖
static map<string,ShapeFactory*> factories;
public:
virtual ~ShapeFactory() {}
friend BadShapeFactoryInitializer;//map和工厂对象的初始化
class BasdShapeCreation:public logic_error{
public:
BagShapeCreation(string type):logic_error("Cannot create type"+type){}
};
static Shape* creatShape(const stirng& id) throw(BadShapeCreation){
if(factories.find(id) != factories.end())//找工厂对象根据传进来的标识符
return factories[id]->create();
else
throw BadShapeCreation(id);
}
};//Shape对象的创建处
//define the static object
map<string,ShapeFactory*> ShapeFactory::factories;
class Circle:public Shape{
Circle();//private constructor
friend class ShapeFactoryInitializer;
class Factory;
friend class Factory;
class Factory:public ShapeFactory{
public:
Shape* create(){return new Circle;}
friend class ShapeFactoryIninitializer;
};
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 ShapeFactoryInitializer;
class Factory;
friend class Factory;
class Factory:public ShapeFactory{
public:
Shape* create(){return new Square;}
friend class ShapeFactoryIninitializer;
};
public:
void draw(){cout << "Square::draw"<<endl;}
void erase(){cout << "Square::erase"<<endl;}
~Square(){cout<<"Square::~Square"<<endl;}
};
//Singleton to initialize the ShapeFactory:
class ShapeFactoryInitializer{
static ShapeFactoryInitializer si;
ShapeFactoryInitializer(){
ShapeFactory::factories["Circle"] = new Circle::Factory;
ShapeFactory::factiories["Square"] = new Square::Factory;
}
~ShpaeFactoryInitializer(){
map<string,ShapeFactory*>::iterator it= ShapeFactory::factories.begin();
while(it != ShapeFactory::factories.end())
delete it++->second;
}
};
//static member definition
ShapeFactoryInitializer ShapeFactoryInitializer::si;
char* si[]= {"Circle","Square","Square","Circle","Circle","Circle","Square"};
int main()
{
vector<Shpae*> shapes;
try{
for(size_t i=0; i <sizeof(si)/sizeof(si[0]); i++)
{
shape.push_back(ShapeFactory::createShape(si[i]));
}catch(ShapeFactory::BadShapeCreation e){
cout<<e.what()<<endl;
return EXIT_FAILURE;
}
for(size_t i = 0; i <shape.size();i++)
{
shapes[i]->draw();
shapes[i]->earse();
}
purge(shapes);
}
}
这里如果不需要创建单独的工厂对象,尽可能使用static工厂模式。