原型模式(Prototype Pattern) 是 创建型设计模式,它用于 克隆对象,而不是重新创建它们。
在 原型模式 中,我们创建一个对象作为原型,并允许其克隆多个副本,而不必重新初始化所有字段。
使用场景
new
关键字创建对象更高效。原型模式包含以下几个主要部分:
clone()
方法,所有要克隆的类都要实现该接口。Prototype
接口,并提供克隆对象的方法。clone()
方法来创建新对象,而不是使用 new
。✅ 优点
new
操作,减少对象创建开销。clone()
方法即可获得新对象。❌ 缺点
clone()
方法:所有类都要 显式实现克隆逻辑,可能增加代码复杂度。代码地址:GitHub
clone()
方法/**
* @author hanson
* @description: 原型接口
* @date 2025-03-23 22:30:55
* @version: 1.0
*/
public interface Prototype {
public Object Clone();
}
/**
* @author hanson
* @description: 体原型类
* @date 2025-03-23 22:31:37
* @version: 1.0
*/
public class Product implements Prototype {
private int id;
private double price;
public Product() {
}
public Product(int id, double price) {
this.id = id;
this.price = price;
}
public int getId() {
return id;
}
public double getPrice() {
return price;
}
@Override
public Object Clone() {
Product object = new Product();
object.id = this.id;
object.price = this.price;
return object;
}
}
/**
* @author hanson
* @description: 模拟客户端
* @date 2025-03-23 22:33:22
* @version: 1.0
*/
public class PrototypePattern {
public static void main(String[] args) {
Product product1 = new Product(2022, 5.28);
System.out.println(product1.getId() + " " + product1.getPrice());
// Product product2 = new Product(2022, 5.28);
Product product2 = (Product) product1.Clone();
System.out.println(product2.getId() + " " + product2.getPrice());
Product product3 = (Product) product1.Clone();
System.out.println(product3.getId() + " " + product3.getPrice());
}
}
运行结果
Clone()
方法,所有要克隆的类都要实现该接口。Prototype
接口,并在 Clone()
方法中复制对象属性。Clone()
方法克隆多个 Product
实例,而不是使用 new
关键字创建对象。clone()
方法复制对象,避免 new
关键字的高成本操作。Cloneable
接口和 Object.clone()
方法 简化克隆操作。✅ 适用场景:
new
关键字带来的性能损耗。创作不易,不妨点赞、收藏、关注支持一下,各位的支持就是我创作的最大动力❤️