大龙的博客

常用链接

统计

最新评论

C++设计模式-Prototype

意图:
用原型指定创建对象的种类,并且通过拷贝函数用这些原型创建对象
适用:
当要实例化的类是在运行时刻指定时,例如:通过动态装载
为了避免创建一个与产品类层次平行的工厂类层次时
当一个类的实例只能有几个不同状态组合中的一种时,建立相应数目的原型并克隆可能要更方便些
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 2010-08-01 15:51 大龙 阅读(300) 评论(0)  编辑 收藏 引用


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