设计模式:原型模式(C++)

概述

原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式之一。

这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。

类图

<<interface>> Prototype Prototype* clone() Person Person* clone() Animal Animal* clone()

以下为 C++ 代码原型的实现方式,与其他(PHP、Java)等不同。例:

cpp 复制代码
class Prototype {
public:
    ~Prototype() {}
    virtual Prototype* clone() = 0;
}
class Person : public Prototype {
    Person* clone() {
        return new Person(*this);
    }
}
class Animal : public Prototype {    
    Animal* clone() {
        return new Animal(*this);
    }
}

C++ 代码,父类 Prototype 通过纯虚函数 clone() 进行派生类对象的复制。父类中 clone() 函数的返回值为Prototype*,而子类为 Person*Animal*,利用了 C++ 的协变特性。

c++ 复制代码
Prototype* p = new Person();
// 此返回值为 Prototype*
p->clone();

Person* p2 = new Person();
// 此返回值为 Person*
p2->clone();
相关推荐
怕浪猫1 天前
领域特定语言(Domain-Specific Language, DSL)
设计模式·程序员·架构
Larcher3 天前
AI Loop:让AI像人一样自主完成任务的核心机制
javascript·人工智能·设计模式
clint4563 天前
C++进阶(1)——前景提要
c++
夜悊3 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴4 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0014 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
咖啡八杯4 天前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
玖玥拾4 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you4 天前
constexpr函数
c++