蜗牛的家
男儿当自强
posts - 48,  comments - 21,  trackbacks - 0
意图:
用原型指定创建对象的种类,并且通过拷贝函数用这些原型创建对象
适用:
当要实例化的类是在运行时刻指定时,例如:通过动态装载
为了避免创建一个与产品类层次平行的工厂类层次时
当一个类的实例只能有几个不同状态组合中的一种时,建立相应数目的原型并克隆可能要更方便些
UML图:

解析:Prototype类似车辆的展示,当你喜欢某款车时,他们会给你一款相同款式的车,像软件中的复制,而不是车展的那辆
//test.h
//////////////////////////////////////////////////////////////////////////
//虚基类,提供基本函数
class Prototype
{
public:
    Prototype()
{}
    
virtual ~Prototype(){}
    
virtual Prototype* Clone() = 0;
}
;

//派生出来的类,实现具体的Clone函数
class ConCreatePrototype1 : public Prototype
{
public:
    ConCreatePrototype1();
    ConCreatePrototype1(
const ConCreatePrototype1&); //拷贝构造函数,通过这个函数实现类的复制
    ~ConCreatePrototype1();
    
    
virtual Prototype* Clone(); //复制出相同对象的接口
}
;


// test.cpp : Defines the entry point for the console application.
//

#include 
"stdafx.h"
#include 
<iostream>
#include 
"stdlib.h"
#include 
"test.h"

using namespace std;
//////////////////////////////////////////////////////////////////////////
ConCreatePrototype1::ConCreatePrototype1()
{
    cout 
<< "construction of ConCreatePrototype1\n";
}

ConCreatePrototype1::
~ConCreatePrototype1()
{
    cout 
<< "destruction of ConCreatePrototype1\n";
}

ConCreatePrototype1::ConCreatePrototype1(
const ConCreatePrototype1&)
{
    cout 
<< "copy a same object as ConCreatePrototype1\n";
}

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

//////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
    Prototype
* pPrototype = new ConCreatePrototype1;
    Prototype
* pPrototype2 = pPrototype->Clone();

    delete pPrototype;
    delete pPrototype2;
    
    system(
"pause");
    
return 0;
}

posted on 2008-08-17 01:16 黑色天使 阅读(504) 评论(0)  编辑 收藏 引用 所属分类: 设计模式

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



<2008年8月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(2)

随笔分类

随笔档案

文章档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜