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


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

    什么是原型模式?

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

    在这里插入图片描述

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

    /*************************************************************************
            > File Name: 8.Clone.cpp
            > Author:
            > Mail:
            > Created Time: Wed Mar 13 17:55:27 2024
     ************************************************************************/
    
    #include 
    #include 
    
    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
  • 相关阅读:
    数据脱敏的功能与技术原理【详解】
    净重新分类指数NRI的计算
    Spring框架在Bean中的管理(第十一课)
    D. Cow and Fields(最短路+思维)
    MySQL 视图(详解)
    超详细的MySQL基本操作
    程序地址空间--Linux
    二叉树的OJ题——C++
    Leetcode39.组合总和
    材料空间「填空解谜」:MIT 利用深度学习解决无损检测难题
  • 原文地址:https://blog.csdn.net/qq_40342400/article/details/136688526