原型模式是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式。
它是用一个已经创建的实例作为原型,通过复制该原型对象来创建一个和原型相同或相似的新对象。在这里,原型实例指定了要创建的对象的种类。用这种方式创建对象非常高效,不需要知道对象创建的细节。
Java中提供了对象的 clone() 方法,所以实现原型模式很简单。他主要就包括了深克隆和浅克隆两种方式。
原型模式的实现
- 创建一个原型类
public class Product implements Cloneable {
Product(){
System.out.println("创建一个原型对象");
}
public Object clone() throws CloneNotSupportedException {
System.out.println("克隆一个原型对象");
return super.clone();
}
}
- 通过浅克隆实现对象的拷贝
public class PrototypeMain {
public static void main(String[] args) throws CloneNotSupportedException {
Product product = new Product();
System.out.println(product);
Product productCloned = (Product) product.clone();
System.out.println(productCloned);
}
}