原型模式(Prototype)

原型模式重在通过对象的自身复制创建新的对象,在c++中和拷贝构造函数的作用是一致的。实现深拷贝

形如:

class Prototype
{
public:
    virtual Prototype *clone() = 0;
};

以字符串string为例,代码:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <assert.h>
#include <cstring>
using namespace std;

class String
{
public:
    String(const char *str)
    {
        assert(str != NULL);
        this->copy(str);
    }
    ~String()
    {
        release();
    }

    String(const String &other)
    {
        this->copy(other._data);
    }

    String &operator=(const String &other)
    {
        // 自己赋值给自己,直接返回
        if (this == &other)
        {
            //printf("自己赋值给自己
");
            return *this;
        }
            
        return operator=(other._data);
    }

    String &operator=(const char *str)
    {
        // 内容相同直接返回
        if (strcmp(_data, str) == 0)
        {
            //printf("内容相同
");
            return *this;
        }

        // 释放原有内存
        release();
        // 深拷贝
        copy(str);
        return *this;
    }

    String * clone()
    {
        String *ret = new String(*this); //调用拷贝构造函数,复制自己
        return ret;
    }

    friend ostream &operator<<(ostream &os, const String &string)
    {
        return os << string._data;
    }

private:
    
    void copy(const char *str)
    {
        _len = strlen(str);
        _data = new char[_len + 1];
        strcpy(_data, str);
    }

    void release()
    {
        if (_data != NULL)
        {
            delete[] _data;
            _data = NULL;
            _len = 0;
        }
    }
private: char *_data; int _len; };
原文地址:https://www.cnblogs.com/hupeng1234/p/6767950.html