设计模式之原型模式

原型模式(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();

    }
}

工作中遇到场景

相关推荐
佛祖让我来巡山12 小时前
设计模式深度解析:策略模式、责任链模式与模板模式
设计模式·责任链模式·策略模式·模版模式
__万波__13 小时前
二十三种设计模式(三)--抽象工厂模式
java·设计模式·抽象工厂模式
转转技术团队13 小时前
VDOM 编年史
前端·设计模式·前端框架
明洞日记15 小时前
【设计模式手册014】解释器模式 - 语言解释的优雅实现
java·设计模式·解释器模式
ZHE|张恒15 小时前
设计模式(十六)迭代器模式 — 统一访问集合元素的方式,不暴露内部结构
设计模式·迭代器模式
未秃头的程序猿19 小时前
🚀 设计模式在复杂支付系统中的应用:策略+工厂+模板方法模式实战
后端·设计模式
雨中飘荡的记忆20 小时前
深入理解设计模式之单例模式
java·设计模式
8***293121 小时前
能懂!基于Springboot的用户增删查改(三层设计模式)
spring boot·后端·设计模式
在未来等你1 天前
AI Agent设计模式 Day 19:Feedback-Loop模式:反馈循环与自我优化
设计模式·llm·react·ai agent·plan-and-execute
兵bing1 天前
设计模式-访问者模式
设计模式·访问者模式