现在的位置: 首页 > 综合 > 正文

设计模式——原型模式_Prototype Pattern

2013年11月24日 ⁄ 综合 ⁄ 共 1032字 ⁄ 字号 评论关闭

原型模式

       Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.(用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。)

UML类图

C++代码实现

#include <iostream>
using namespace std;

class Prototype {
public:
	virtual Prototype* clone() const = 0;

};

class ConcretePrototype : public Prototype {
public:
	ConcretePrototype() { _count = 1; }
	ConcretePrototype* clone() const { return new ConcretePrototype(*this); }
	ConcretePrototype(const ConcretePrototype& cp) {
		_count = cp._count;	
		//cout << "ConcretePrototype copy" << endl; 
	}
	void SetCount(int i) { _count = i; }
	void Print() { cout << _count << endl; }

private:
	int _count;
};


#include "Prototype.h"


int main()
{
	ConcretePrototype* p = new ConcretePrototype();
	
	//不通过new关键字来产生一个对象,而是通过对象复制来实现的模式 ————原型模式
	for (int i=0; i<10; ++i)
	{
		ConcretePrototype* p1 = p->clone();
		p1->SetCount(i);
		p1->Print();
	}
	
	delete p;
	return 0;
}

Prototype 模式通过复制原型(Prototype)而获得新对象创建的功能,这里Prototype 本身就是 “对象工厂”(因为能够生产对象),实际上Prototype模式和 Builder模 式、AbstractFactory 模式都是通过一个类 (对象实例)来专门负责对象的创建工作 (工厂对象),它们之间的区别是:Builder模式重在复杂对象的一步步创建(并不直接返回对象),AbstractFactory
 模式重在产生多个相互依赖类的对象,而 Prototype  模式重在从自身复制己创建新类。 

抱歉!评论已关闭.