Benjamin

静以修身,俭以养德,非澹薄无以明志,非宁静无以致远。
随笔 - 397, 文章 - 0, 评论 - 196, 引用 - 0
数据加载中……

设计模式之工厂(factory)模式(一)

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()可以访问它的构造函数。这样做的缺点:一旦新类型被加入到这种结构来时,必须更新基类。

posted on 2009-04-12 16:37 Benjamin 阅读(391) 评论(0)  编辑 收藏 引用 所属分类: C/C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理