原型模式C++

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

原型模式结构图

image

原型模式基本代码

原型模式其实就是从一个对象再创建另一个可定制的对象,而且不需知道任何创建的细节。

#include <iostream>
#include <string>
#include "string.h"
using namespace std;

class Prototype { // 原型类
private:
    string id;
    char* str;
public:
    virtual ~Prototype() {
        delete[] str;
    }
    virtual Prototype* Clone() = 0;
    Prototype(string i, char* s) { 
        id = I; 
        int len = strlen(s);
        str = new char[len+1];  // 深度复制
        cout << &str << endl;   // 输出str的地址,作为对比
        strcpy(str, s);
        str[len] = '\0';
    }
    string GetId() { return id; }
    char* GetStr() { return str; }
};

class ConcretePrototype1 : public Prototype {
public:
    ConcretePrototype1(string id, char* s) : Prototype(id, s) {}
    ConcretePrototype1(ConcretePrototype1& cp1) : Prototype(cp1.GetId(), cp1.GetStr()){} // 复制构造函数,实现深度复制
    Prototype* Clone() {
        return new ConcretePrototype1(*this);
    }
};

class ConcretePrototype2 : public Prototype {
public:
    ConcretePrototype2(string id, char* s) : Prototype(id, s) {}
    ConcretePrototype2(ConcretePrototype2& cp2) : Prototype(cp2.GetId(), cp2.GetStr()){} // 复制构造函数,实现深度复制
    ConcretePrototype2* Clone() {
        return new ConcretePrototype2(*this);
    }
};

int main() {
    char* s = "Hello";
    Prototype* p = new ConcretePrototype1("1", s); // 0x7f99ad501060
    Prototype* c = p->Clone();   // 0x7f99ad501090
    cout << c->GetId() << endl;  // 1
    cout << c->GetStr() << endl; // Hello

    delete p;
    delete c;

    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,730评论 8 265
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,199评论 19 139
  • 设计模式汇总 一、基础知识 1. 设计模式概述 定义:设计模式(Design Pattern)是一套被反复使用、多...
    MinoyJet阅读 3,997评论 1 15
  • 今天收拾书柜的时候,我发现了这本尼采的《查拉图斯特拉如是说》。 这本书,是我读高中的时候买的。买这本书因为本着对于...
    YZ_振阅读 338评论 0 0
  • 一个巨大的问号 躺在母亲的羊水里 十个月后 一个惊叹号吓得哇哇大哭 就这样惊叹着 时而一个痛苦的分号 蹲在地上诉说...
    冷冬年阅读 487评论 0 3