设计模式之原型模式

原型模式

目的:

Specify the kinds of objects to create using a prototypical instance, and create
new objects by copying this prototype.

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

C++实现要点:

1.原型模式中,Client并不知道要克隆对象的实际类型,只需知道基类类型即可。
2.克隆对象比直接创建对象的优点在于,克隆是将原有对象的行为属性带到了新的对象中。
3.C++没有克隆方法,要克隆一个对象,需要借助拷贝构造函数(Copy Constructor)来实现。拷贝构造函数中实现拷贝对象有浅拷贝和深拷贝:
  浅拷贝是指对象复制时,只是对于对象中的数据成员进行值拷贝;深拷贝是指对象赋值时,对于对象的简单数据成员进行值拷贝,对于对象中的动态成员(堆或者其他系统资源),要重新分配动态空间。
  当类不定义拷贝构造函数的时候,编译器会自动生一个构造函数,叫做默认拷贝构造函数。默认拷贝构造函数使用浅拷贝方式。如果类中含有动态数据成员,就必须使用深拷贝方式实现拷贝构造函数,否则,在销毁对象时,两个对象的析构函数将对同一个内存空间释放两次,产生运行时错误。
 
//Prototype.h

#include <string>
using namespace std;

class Prototype
{
public:
    virtual Prototype *clone()=0;
    virtual void show()=0;
};

class concretePrototype1:public Prototype
{
private:
    string m_str;
public:
    concretePrototype1();
    concretePrototype1(string cstr);
    concretePrototype1(const concretePrototype1 &c);
    virtual Prototype *clone();
    virtual void show();

};

class concretePrototype2:public Prototype
{
private:
    string m_str;
public:
    concretePrototype2(string cstr);
    concretePrototype2(const concretePrototype2 &c);
    virtual Prototype *clone();
    virtual void show();
};

//Prototype.cpp

#include "Prototype.h"
#include <iostream>
/*
using namespace std;
concretePrototype1::concretePrototype1()
{
    cout<<"default the concretePrototype1"<<endl;
    this->m_str="default type1";
}

concretePrototype1::concretePrototype1(string cstr)
{
    cout<<"construct the concretePrototype1"<<endl;
    this->m_str=cstr;
}
concretePrototype1::concretePrototype1(const concretePrototype1 &c)
{
    cout<<"copy the concretePrototype1"<<endl;
    this->m_str=c.m_str;

}
Prototype *concretePrototype1::clone()
{
    cout<<"clone the concretePrototype1"<<endl;
    return new concretePrototype1(*this);
}

void concretePrototype1::show()
{
    cout<<"show the concretePrototype1"<<endl;
    cout<<this->m_str<<endl;
}

concretePrototype2::concretePrototype2(string cstr)
{
    this->m_str=cstr;
}
concretePrototype2::concretePrototype2(const concretePrototype2 &c)
{
    cout<<"copy the concretePrototype2"<<endl;
    this->m_str=c.m_str;
}
Prototype *concretePrototype2::clone()
{
    return new concretePrototype2(*this);
}

void concretePrototype2::show()
{
    cout<<this->m_str<<endl;
}
//main.cpp

#include “Prototype.h”

void main()
{
    concretePrototype1 cp1;
    concretePrototype1 cp2=cp1;                  //原来的调用复制构造函数

    cp1.show();                         
    cp2.show();
    
    Prototype *cp3=new concretePrototype1("concretePrototype1");  //指针的类型是父类
    cp3->show();

    Prototype *cp4=cp3->clone();
    cp4->show();
    delete cp3;
    cp3=NULL;
    cp4->show();

       return ;
}
View Code

 

参考资料

设计模式C++描述----08.原型(Prototype)模式

C++设计模式-Prototype

C++设计模式-Prototype

我所理解的设计模式(C++实现)——原型模式(Prototype Pattern)

 

posted on 2014-07-26 22:47  鹰之翔  阅读(154)  评论(0编辑  收藏  举报

导航