设计模式之Prototype Pattern

摘自:《设计模式精解—GoF 23种设计模式解析附C++实现源码》

URL: http://www.mscenter.edu.cn/blog/k_eckel

Prototype模式提供了一个通过已存在对象进行新对象创建的接口(Clone), Clone()实现和具体的语言相关,在C++中我们将通过拷贝构造函数实现之。

1 //Prototype.h
2 #ifndef _PROTOTYPE_H_
3 #define _PROTOTYPE_H_
4
5 class Prototype{
6 public:
7 virtual ~Prototype();
8 virtual Prototype *Clone() const = 0;
9 protected:
10 Prototype();
11 };
12
13 class ConcretePrototype: public Prototype{
14 public:
15 ConcretePrototype();
16 ConcretePrototype(const ConcretePrototype & cp);
17 ~ConcretePrototype();
18 Prototype *Clone() const;
19 protected:
20 private:
21 };
22
23 #endif //~_PROTOTYPE_H_
//Prototype.cpp
#include "Prototype.h"
#include
<iostream>
using namespace std;

Prototype::Prototype(){
}

Prototype::
~Prototype(){
}

Prototype
*Prototype::Clone() const{
return 0;
}

ConcretePrototype::ConcretePrototype(){
}

ConcretePrototype::
~ConcretePrototype(){
}

ConcretePrototype::ConcretePrototype(
const ConcretePrototype & cp){
cout
<<"ConcretePrototype Copy ..."<<endl;
}

Prototype
*ConcretePrototype::Clone() const{
return new ConcretePrototype(*this);
}

posted on 2011-06-14 09:08  Joshua Leung  阅读(175)  评论(0编辑  收藏  举报

导航