Prototype模式

117 阅读2分钟

摘要

Prototype模式是一种创建型设计模式,它通过复制已有实例来生成新对象,而非通过类实例化。本文将详细介绍为什么要使用Prototype模式、如何使用它以及它的优缺点,同时通过代码示例帮助你更好地理解。

架构图

structure-2x.png

为什么要使用Prototype模式?

当创建对象的成本较高,例如对象构建过程复杂、需要大量资源时,Prototype模式能够显著提高程序的性能。通过复制已有实例而非重新构建,它可以减少CPU、内存等资源的消耗。此外,当需要动态地创建对象类型时,Prototype模式也能提供良好的灵活性。

如何使用Prototype模式?

要使用Prototype模式,首先需要创建一个原型接口(Prototype Interface),用于定义复制(clone)方法。然后,实现该接口的具体原型类(Concrete Prototype)将实现该复制方法,创建新对象。最后,通过客户端调用复制方法来生成新对象。

Prototype模式的优缺点

优点

  1. 创建对象性能更高,尤其在创建过程成本较高时。
  2. 适用于动态创建对象类型的场景。
  3. 降低内存和CPU资源的消耗。

缺点

  1. 复制过程可能涉及到深拷贝和浅拷贝问题,需要谨慎处理。
  2. 实现复制方法可能需要额外的编程工作。

代码示例

public abstract class Prototype implements Cloneable {

    public abstract Prototype clone() throws CloneNotSupportedException;
}

public class ConcretePrototypeA extends Prototype {

    private int value;

    public ConcretePrototypeA(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    @Override
    public Prototype clone() throws CloneNotSupportedException {
        return (ConcretePrototypeA) super.clone();
    }
}

public class ConcretePrototypeB extends Prototype {

    private String value;

    public ConcretePrototypeB(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public Prototype clone() throws CloneNotSupportedException {
        return (ConcretePrototypeB) super.clone();
    }
}

public class Client {
    public static void main(String[] args) {
        ConcretePrototypeA prototypeA = new ConcretePrototypeA(10);
        ConcretePrototypeB prototypeB = new ConcretePrototypeB("Hello World");

        try {
            ConcretePrototypeA clonedPrototypeA = (ConcretePrototypeA) prototypeA.clone();
            ConcretePrototypeB clonedPrototypeB = (ConcretePrototypeB) prototypeB.clone();

            System.out.println(clonedPrototypeA.getValue());
            System.out.println(clonedPrototypeB.getValue());
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

在这个示例中,我们首先定义了一个抽象的原型类(Prototype),它实现了Java的Cloneable接口。然后,我们创建了两个具体的原型类(ConcretePrototypeA和ConcretePrototypeB),它们分别扩展了抽象的原型类,并实现了clone()方法。最后,在客户端(Client)中,我们创建了原型实例并调用了它们的clone()方法生成新的对象。

参考资料

refactoring.guru/design-patt…