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 方法较隐蔽,不如构造器直观

✅ 使用建议

  • 当需要频繁创建结构相似对象,或者对象构建代价大时(如图形编辑器中的图形、工作流节点等),原型模式是高效之选
相关推荐
ZLRRLZ12 分钟前
【C++】C++11
开发语言·c++
ciku21 分钟前
Spring AI Starter和文档解读
java·人工智能·spring
o0向阳而生0o21 分钟前
93、23种设计模式之抽象工厂模式
设计模式·抽象工厂模式
全栈软件开发22 分钟前
PHP域名授权系统网站源码_授权管理工单系统_精美UI_附教程
开发语言·ui·php·php域名授权·授权系统网站源码
誰能久伴不乏27 分钟前
Qt 动态属性(Dynamic Property)详解
开发语言·qt
程序猿阿越31 分钟前
Kafka源码(三)发送消息-客户端
java·后端·源码阅读
whitepure36 分钟前
万字详解Java中的运算
java
AAA修煤气灶刘哥38 分钟前
搞定 Redis 不难:从安装到实战的保姆级教程
java·redis·后端
MrSYJ41 分钟前
全局和局部AuthenticationManager
java·后端·程序员