Skip to content

原型模式

意图

通过复制已有实例来创建新对象,而非从零 new。适合创建成本大、或状态与某模板相近的对象。

类图

Java 示例

实现 Cloneable(浅拷贝)

java
public class ReportTemplate implements Cloneable {
    private String title;
    private java.util.List<String> sections;

    public ReportTemplate(String title, java.util.List<String> sections) {
        this.title = title;
        this.sections = sections;
    }

    @Override
    public ReportTemplate clone() {
        try {
            return (ReportTemplate) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new AssertionError(e);
        }
    }
}

浅拷贝下 sections 与原对象共享同一列表;需深拷贝时应在 clone 里复制集合元素或用手动拷贝构造。

拷贝构造(更可控)

java
public ReportTemplate(ReportTemplate other) {
    this.title = other.title;
    this.sections = new java.util.ArrayList<>(other.sections);
}

适用场景

对象创建昂贵、或需要保留当前状态副本(撤销栈、文档副本等)。注意 clone 与 final 字段深拷贝边界。

进入第三篇:适配器模式