设计模式之原型模式

原型模式(Prototype Pattern)

定义

通过复制现有对象来创建新对象,同时又保持了封装性。

通过复制现有对象来创建新的对象,而不是通过实例化新对象。这样可以提高对象创建的效率,尤其是在对象的创建过程比较昂贵或复杂的情况下

使用场景

  • 当一个对象的构建代价过高时。例如某个对象里面的数据需要访问数据库才能拿到,而我们却要多次构建这样的对象。
  • 当构建的多个对象,均需要处于某种原始状态时,就可以先构建一个拥有此状态的原型对象,其他对象基于原型对象来修改。

主要角色

  1. 抽象原型(Prototype): 定义用于复制自身的接口。通常包含一个克隆方法(Clone),该方法用于创建当前对象的副本。
  2. 具体原型(Concrete Prototype): 实现抽象原型接口,提供实际的克隆方法。客户端可以通过调用克隆方法来复制具体原型的实例。

类图

示例代码

java 复制代码
public interface ProductPrototype {
    ProductPrototype copy();
}
java 复制代码
@Data
public class Product implements ProductPrototype {
    private String category;
    private String seller;
    private String brand;
    private String name;
    private double price;
    private String description;

    public Product(String category, String seller, String brand) {
        this.category = category;
        this.seller = seller;
        this.brand = brand;
    }

    @Override
    public Product copy() {
        return new Product(this.category, this.seller, this.brand);
    }


    public void showDetails() {
        System.out.println(JSON.toJSONString(this));
    }
}
java 复制代码
public class Client {
    public static void main(String[] args) {
        Product product = new Product("手机", "小米旗舰店", "小米");
        Product note12 = product.copy();
        note12.setName("红米Note12");
        note12.setPrice(599.0);
        note12.showDetails();
        Product pro13 = product.copy();
        pro13.setName("小米Pro13");
        pro13.setPrice(1499.0);
        pro13.showDetails();

    }
}

工作中遇到场景

相关推荐
IT灰猫2 小时前
C++轻量级配置管理器升级版
开发语言·c++·设计模式·配置管理·ini解析
大飞pkz3 小时前
【设计模式】题目小练2
开发语言·设计模式·c#·题目小练
不一样的少年_7 小时前
Vue3 后台分页写腻了?我用 1 个 Hook 删掉 90% 重复代码(附源码)
前端·vue.js·设计模式
A阳俊yi7 小时前
设计模式——七大常见设计原则
设计模式
青草地溪水旁9 小时前
设计模式(C++)详解——建造者模式(1)
c++·设计模式·建造者模式
念何架构之路15 小时前
Go语言设计模式(七)组合模式
设计模式·组合模式
m0_6038887118 小时前
Prototype-Aware Multimodal Alignment for Open-Vocabulary Visual Grounding
ai·原型模式·论文速览
易元1 天前
模式组合应用-外观模式
后端·设计模式
大飞pkz1 天前
【设计模式】题目小练1
开发语言·设计模式·c#·题目小练
烛阴1 天前
【TS 设计模式完全指南】TypeScript 装饰器模式的优雅之道
javascript·设计模式·typescript