通过复制现有对象来创建新对象,同时又保持了封装性。
通过复制现有对象来创建新的对象,而不是通过实例化新对象。这样可以提高对象创建的效率,尤其是在对象的创建过程比较昂贵或复杂的情况下
public interface ProductPrototype {
ProductPrototype copy();
}
@Data
public class Product implements ProductPrototype {
private String category;
private String seller;
private String brand;
private String name;
private double price;
private String description;
public Product(String category, String seller, String brand) {
this.category = category;
this.seller = seller;
this.brand = brand;
}
@Override
public Product copy() {
return new Product(this.category, this.seller, this.brand);
}
public void showDetails() {
System.out.println(JSON.toJSONString(this));
}
}
public class Client {
public static void main(String[] args) {
Product product = new Product("手机", "小米旗舰店", "小米");
Product note12 = product.copy();
note12.setName("红米Note12");
note12.setPrice(599.0);
note12.showDetails();
Product pro13 = product.copy();
pro13.setName("小米Pro13");
pro13.setPrice(1499.0);
pro13.showDetails();
}
}