码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式之原型模式(Prototype)

时间:2016-05-07 10:26:49      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

原型模式:

优点:

使用拷贝比new一个对象的开销要小


代码示例:

Prototype.h

#ifndef PROTOTYPE_H
#define PROTOTYPE_H

/**
 *1、声明一个抽象基类,并定义clone()函数为纯虚函数。
 *2、实例化各个子类,并且实现复制构造函数,并实现clone()函数
 */

class Resume
{
public:
    Resume(){}
    virtual ~Resume(){}
    virtual Resume *clone(){return 0;}
    virtual void set(char *){}
    virtual void show(){}


protected:
    char *name;
};

class ResumeA : public Resume
{
public:
    ResumeA(const char *);
    ResumeA(const ResumeA &);
    ~ResumeA();
    ResumeA *clone();
    void show();
};

class ResumeB : public Resume
{
public:
    ResumeB(const char *);
    ResumeB(const ResumeB &);
    ~ResumeB();
    ResumeB *clone();
    void show();
};
#endif // PROTOTYPE_H


Prototype.cpp

#include "prototype.h"
#include <string.h>
#include <iostream>
#include <stdio.h>

ResumeA::ResumeA(const char * str)
{
    if(str)
    {
        name = new char[1];
        name[0] = '\0';
    }
    else
    {
        name = new char[strlen(str)+1];
        strcpy(name, str);
    }
}

ResumeA::ResumeA(const ResumeA &r)
{
    name = new char[strlen(r.name)+1];
    strcpy(name, r.name);
}

ResumeA::~ResumeA()
{
    delete []name;
}

ResumeA *ResumeA::clone()
{
    return new ResumeA(*this);
}

void ResumeA::show()
{
    std::cout << "ResumeA name :" << name << std::endl;
}


ResumeB::ResumeB(const char * str)
{
    if(str)
    {
        name = new char[1];
        name[0] = '\0';
    }
    else
    {
        name = new char[strlen(str)+1];
        strcpy(name, str);
    }
}

ResumeB::ResumeB(const ResumeB &r)
{
    name = new char[strlen(r.name)+1];
    strcpy(name, r.name);
}

ResumeB::~ResumeB()
{
    delete []name;
}

ResumeB *ResumeB::clone()
{
    return new ResumeB(*this);
}

void ResumeB::show()
{
    std::cout << "ResumeB name :" << name << std::endl;
}

main.cpp

#include <iostream>

#include "prototype.h"


int main()
{
    Resume *r1 = new ResumeA("A");
    Resume *r2 = new ResumeB("B");
    Resume *r3 = r1->clone();
    Resume *r4 = r2->clone();

    delete r1;
    delete r2;
    r3->show();
    r4->show();


    return 0;
}



设计模式之原型模式(Prototype)

标签:

原文地址:http://blog.csdn.net/fu1201520/article/details/51330625

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!