大话设计模式--原型模式 Prototype -- C++实现

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

注意: 拷贝的时候是浅拷贝 还是 深拷贝, 来考虑是否需要重写拷贝构造函数。

关键在于: virtual Prototype* clone();  克隆函数。。。返回一个克隆的对象。

 

实例: 以深拷贝为例

prototype.h   prototype.cpp

#ifndef PROTOTYPE_H
#define PROTOTYPE_H

class Prototype
{
public:
    int a;
    char *str;
    Prototype(int b, char* cstr);
    Prototype(const Prototype &cp);
    ~Prototype();
    void show();
    virtual Prototype* clone();
};

#endif // PROTOTYPE_H
#include "prototype.h"
#include <string.h>
#include <stdio.h>

Prototype::Prototype(int b, char* cstr)
{
    a = b;
    str = new char[b];
    strcpy(str, cstr);
}

Prototype::~Prototype()
{
    delete str;
}

Prototype::Prototype(const Prototype &cp)
{
    a = cp.a;
    str = new char[a];
    if(str!=0)
        strcpy(str, cp.str);
}

Prototype* Prototype::clone()
{
    return new Prototype(a, str);
}

void Prototype::show()
{
    printf("a: %d, str: %s\n", a, str);
}


main.cpp

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

using namespace std;

int main()
{
    cout << "Prototype test !" << endl;

    Prototype *p = new Prototype(6, "hello");
    Prototype *p1 = p->clone();
    p1->show();

    return 0;
}



 

 

转载于:https://www.cnblogs.com/xj626852095/p/3648195.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值