Skip to content

原型模式

基础概念

什么是原型模式?

答案: 原型模式(Prototype Pattern)用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。

使用场景

  • 对象创建成本较大
  • 需要大量相似对象
  • 需要保护原始对象

优点

  • 性能优良
  • 简化对象创建

缺点

  • 需要实现克隆方法
  • 深拷贝复杂

实现方式

java
// 原型接口
public interface Prototype extends Cloneable {
    Prototype clone();
}

// 具体原型
public class ConcretePrototype implements Prototype {
    private String field;

    public ConcretePrototype(String field) {
        this.field = field;
    }

    @Override
    public Prototype clone() {
        try {
            return (Prototype) super.clone();
        } catch (CloneNotSupportedException e) {
            return null;
        }
    }
}

// 深拷贝示例
public class DeepPrototype implements Cloneable {
    private String name;
    private Address address;

    @Override
    public DeepPrototype clone() {
        try {
            DeepPrototype cloned = (DeepPrototype) super.clone();
            cloned.address = this.address.clone();  // 深拷贝
            return cloned;
        } catch (CloneNotSupportedException e) {
            return null;
        }
    }
}

练习题

  1. 浅拷贝和深拷贝的区别?
  2. 如何实现深拷贝?
  3. 原型模式的应用场景?

Released under the MIT License.