23种设计模式-创建型模式之原型模式(Java版本)

Java 原型模式(Prototype Pattern)详解

🧬 什么是原型模式?

原型模式用于通过复制已有对象的方式创建新对象,而不是通过 new 关键字重新创建。

核心是:通过克隆(clone)已有对象,以便快速创建多个相似对象。


🧠 使用场景

  • 创建对象成本较高(如数据库连接、大对象)
  • 想避免重复初始化
  • 希望对象可以被"快速复制"

🏗️ 模式结构

  • Prototype(原型接口)
  • ConcretePrototype(具体原型)
  • Client(客户端)

✅ 示例:克隆简历

原型接口

java 复制代码
public interface Prototype extends Cloneable {
    Prototype clone();
}

具体原型类

public 复制代码
    private String name;
    private String gender;
    private String experience;

    public Resume(String name, String gender, String experience) {
        this.name = name;
        this.gender = gender;
        this.experience = experience;
    }

    public void setExperience(String experience) {
        this.experience = experience;
    }

    @Override
    public Prototype clone() {
        try {
            return (Prototype) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException("Clone failed", e);
        }
    }

    @Override
    public String toString() {
        return "Resume [name=" + name + ", gender=" + gender + ", experience=" + experience + "]";
    }
}

客户端调用

public 复制代码
    public static void main(String[] args) {
        Resume resume1 = new Resume("Alice", "Female", "3 years at Google");
        Resume resume2 = (Resume) resume1.clone();
        resume2.setExperience("5 years at Amazon");

        System.out.println(resume1);
        System.out.println(resume2);
    }
} 

🔍 深拷贝 vs 浅拷贝

  • 浅拷贝:拷贝对象本身,引用类型仍指向同一内存
  • 深拷贝:连引用对象也一并复制,互不影响

🧩 优点

  • 避免重复初始化,提升性能

  • 简化对象创建过程

  • 可动态添加新对象,不需依赖类结构

⚠️ 缺点

  • 深拷贝实现复杂

  • 涉及对象引用时需小心内存问题

  • clone 方法较隐蔽,不如构造器直观

✅ 使用建议

  • 当需要频繁创建结构相似对象,或者对象构建代价大时(如图形编辑器中的图形、工作流节点等),原型模式是高效之选
相关推荐
TT哇2 分钟前
【Java EE初阶】计算机是如何⼯作的
java·redis·java-ee
专注VB编程开发20年9 分钟前
javascript的类,ES6模块写法在VSCODE中智能提示
开发语言·javascript·vscode
Fireworkitte7 小时前
Apache POI 详解 - Java 操作 Excel/Word/PPT
java·apache·excel
weixin-a153003083167 小时前
【playwright篇】教程(十七)[html元素知识]
java·前端·html
DCTANT7 小时前
【原创】国产化适配-全量迁移MySQL数据到OpenGauss数据库
java·数据库·spring boot·mysql·opengauss
Touper.7 小时前
SpringBoot -- 自动配置原理
java·spring boot·后端
黄雪超7 小时前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm
ThetaarSofVenice7 小时前
对象的finalization机制Test
java·开发语言·jvm
思则变8 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
GodKeyNet8 小时前
设计模式-模板模式
设计模式·模板模式