设计模式之原型模式

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

    }
}

工作中遇到场景

相关推荐
vker1 小时前
第 1 天:单例模式(Singleton Pattern)—— 创建型模式
java·设计模式
晨米酱20 小时前
JavaScript 中"对象即函数"设计模式
前端·设计模式
数据智能老司机1 天前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机1 天前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——性能模式
python·设计模式·架构
使一颗心免于哀伤1 天前
《设计模式之禅》笔记摘录 - 21.状态模式
笔记·设计模式
数据智能老司机2 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机2 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
烛阴2 天前
【TS 设计模式完全指南】懒加载、缓存与权限控制:代理模式在 TypeScript 中的三大妙用
javascript·设计模式·typescript