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

原型模式:

优点:

使用拷贝比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;
}



你可能感兴趣的:(原型模式)