工厂模式

工厂模式强制用一个通用的工厂(factory)来创建对象,而不允许将创建对象的代码散布于整个系统。如果程序中所有需要创建对象的代码都转到这个工厂执行,那么再增加新对象时的所要做的全部工作就是只需修改工厂。这种设计是众所周知的工厂方法的一种变体。

#include <iostream>
#include <stdexcept>
#include <cstddef>
#include <string>
#include <vector>
//#include "../purge.h"
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() {} // 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::~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;
		/* purge(shapes); */
		return EXIT_FAILURE;
	}
	for(size_t i = 0; i < shapes.size(); i++) {
		shapes[i]->draw();
		shapes[i]->erase();
	}
	/* purge(shapes); */
}

在添加新的Shape类型时,函数factory()是当前系统中惟一需要修改的代码。

选自《C++编程思想》。

转载于:https://www.cnblogs.com/chinaxmly/archive/2012/10/01/2709796.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值