zoukankan      html  css  js  c++  java
  • 大话设计模式--原型模式 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
    ", 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;
    }
    



     

  • 相关阅读:
    一周以来工作总结关于位图索引
    再学学表的分区
    PostgreSQL学习笔记
    通过vc助手设置快捷注释
    c语言中unsigned类型和普通类型间的转换
    LVS环境搭建入门
    java学习路线
    linux下删除当前文件夹中按时间排序的前N个文件夹
    RHEL下安装jdk和tomcat
    TDD 强迫你 Program to Interface
  • 原文地址:https://www.cnblogs.com/xj626852095/p/3648195.html
Copyright © 2011-2022 走看看