一、简介
Prototype 模式提供了自我复制的功能,即新对象的创建可以通过已有对象进行创建(Clone),实现和具体的实现语言相关,在C++中通过拷贝构造函数(Copy Constructor)实现。拷贝构造函数中浅层拷贝和深层拷贝曾经是很多程序员的噩梦,也是修改或释放资源时程序崩溃的根源之一。
在此只进行浅层拷贝的实现(int number),不涉及深层拷贝(主要要指有指针、复合对象的情况)。通过编译器提供的默认的拷贝构造函数(按位拷贝)的方式进行实现,重点放在Prototype 模式本身的思想。
二、详解
1、代码实现
(1)代码prototype.h:
#ifndef _PROTOTYPE_H_
#define _PROTOTYPE_H_
class Prototype
{
public:
virtual ~Prototype();
virtual Prototype *Clone() const = 0;
int number;
protected:
Prototype();
private:
};
class ConcretePrototype : public Prototype
{
public:
ConcretePrototype();
ConcretePrototype(const ConcretePrototype &cp);
~ConcretePrototype();
Prototype *Clone() const;
};
#endif
(2)代码prototype.cpp:
#include<iostream>
#include "prototype.h"
using namespace std;
Prototype::Prototype()
{
cout<<"---Prototype constructor"<<endl;
number = 100;
}
Prototype::~Prototype()
{
}
Prototype *Prototype::Clone() const
{
return 0;
}
ConcretePrototype::ConcretePrototype()
{
cout<<"---ConcretePrototype constructor"<<endl;
}
ConcretePrototype::ConcretePrototype(const ConcretePrototype &cp)
{
cout<<"---ConcretePrototype copy..."<<endl;
}
ConcretePrototype::~ConcretePrototype()
{
}
Prototype *ConcretePrototype::Clone() const
{
cout<<"---Clone()"<<endl;
return new ConcretePrototype(*this);
}
(3)代码main.cpp:
#include <iostream>
#include "prototype.h"
using namespace std;
int main()
{
Prototype *p_one = new ConcretePrototype();
cout<< "before clone:" << p_one->number <<endl;
Prototype *p_two = p_one->Clone();
cout<< "clone:" << p_two->number <<endl;
p_two->number = 200;
cout<< "----------------------" <<endl;
cout<< "origin:" << p_one->number <<endl;
cout<< "clone:" << p_two->number <<endl;
delete p_one;
delete p_two;
return 0;
}
(4)makefile:
CFLAGS = -g
DEFINED = #-D _VERSION
LIBS =
CC = g++
INCLUDES = -I./
OBJS= main.o prototype.o
TARGET= main
all:$(TARGET)
$(TARGET):$(OBJS)
$(CC) $(CFLAGS) -o $@ $(OBJS)
.SUFFIXES:.o .h
.SUFFIXES:.cpp .o
.cpp.o:
$(CC) $(DEFINED) -c $(CFLAGS) -o $@ $<
ok:
./$(TARGET)
clean:
rm -f $(OBJS) $(TARGET) core *.log
2、运行结果
(centos6.3系统中运行结果:)
三、总结
(1)Prototype 模式通过复制原型(Prototype)而获得新对象创建的功能,这里 Prototype 本身就是“对象工厂”(因为能够生产对象)。实际上 Prototype 模式和 Builder 模式、AbstractFactory 模式都是通过一个类(对象实例)来专门负责对象的创建工作(工厂对象),它们之间的区别是:Builder 模式重在复杂对象的一步步创建(并不直接返回对象),AbstractFactory 模式重在产生多个相互依赖类的对象,而Prototype 模式重在从自身复制自己创建新类。
(2)源码已经打包上传到csdn上可登录下载(http://download.csdn.net/detail/taiyang1987912/8407417)。