定义


原型模式

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

实现

public class Product implements Cloneable {
	private int id;
	private String name;
	
	public Product(int id, String name) {
		this.id = id;
		this.name = name;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}
 
Product prototype = new Product(1, "A");
 
Product product1 = prototype.clone();
 
Product product2 = prototype.clone();
product1.setId(2);

优点

  • 性能较好,基于内存拷贝。
  • 不使用构造函数,简化了对象创建。
  • 可以方便的保留对象的状态。
    缺点
  • 默认是浅拷贝,当对象层级嵌套较深时,拷贝逻辑会十分复杂且容易遗漏。
  • 对象存在循环引用时可能会出现死循环或栈溢出。
  • 侵入性较强,实现克隆时需要修改类的实现。