原型模式(Clone)——创建型模式

原型模式(clone)——创建型模式

什么是原型模式?

原型模式是一种创建型设计模式, 使你能够复制已有对象, 而又无需依赖它们所属的类

在这里插入图片描述

总结:需要在继承体系下,实现一个clone接口,在这个方法中以本身作为拷贝源,调用自身拷贝构造函数,并返回新对象地址(用基类指针接收)。

/*************************************************************************
        > File Name: 8.Clone.cpp
        > Author:
        > Mail:
        > Created Time: Wed Mar 13 17:55:27 2024
 ************************************************************************/

#include <iostream>
#include <vector>

using namespace std;

class Shape {
private:
    int x, y;
public:
    Shape() = default;
    Shape(const Shape &obj) {
        x = obj.x;
        y = obj.y;
    }
    virtual Shape* clone() = 0;
};

class Rectangle : public Shape {
private:
    int width, height;
public:
    Rectangle() = default;
    Rectangle(const Rectangle &obj) : Shape(obj) {
        width = obj.width;
        height = obj.height;
    }
    Shape* clone() override {
        return new Rectangle(*this);
    }
};

class Circle : public Shape {
private:
    int radius;
public:
    Circle() = default;
    Circle(const Circle &obj) : Shape(obj) {
        radius = obj.radius;
    }
    Shape* clone() override {
        return new Circle(*this);
    }
};

vector<Shape *> vec;
vector<Shape *> backup;

int main() {
    Rectangle *rec = new Rectangle();
    vec.push_back(rec);
    Circle *cir = new Circle();
    vec.push_back(cir);

    for (int i = 0; i < vec.size(); ++i) {
        backup.push_back(vec[i]->clone());
    }
    return 0;
}

相关推荐

  1. 设计模式创建模式原型模式

    2024-03-17 05:26:02       45 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-17 05:26:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-17 05:26:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-17 05:26:02       82 阅读
  4. Python语言-面向对象

    2024-03-17 05:26:02       91 阅读

热门阅读

  1. 封装promise请求方式

    2024-03-17 05:26:02       48 阅读
  2. OLLAMA:如何像云端一样运行本地大语言模型

    2024-03-17 05:26:02       44 阅读
  3. alibaba cloud linux 3 安装 psql 16

    2024-03-17 05:26:02       46 阅读
  4. Python强大的库和框架——TensorFlow

    2024-03-17 05:26:02       44 阅读
  5. springBoot整合Redis(四、整合redis 实现分布式锁)

    2024-03-17 05:26:02       45 阅读
  6. lammps从NVT或者NPT切换到NVE时温度持续上升

    2024-03-17 05:26:02       42 阅读
  7. Python列表详解

    2024-03-17 05:26:02       48 阅读
  8. 【C语言】打印1-100之间所有3的倍数的数字

    2024-03-17 05:26:02       42 阅读