通过一个原型对象来指明所要创建的对象的类型,然后用复制这个原型对象的办法创建出更多同类型的对象。
public interface Prototype extends Cloneable {
public Object clone();
}
public class ConcreatePrototype implements Prototype {
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}
public class Client {
public static void main(String[] args) {
Prototype prototype = new ConcreatePrototype();
System.out.println(prototype);
Prototype prototype2 = (Prototype) prototype.clone();
System.out.println(prototype2);
/*克隆对象与原对象不是同一个对象*/
System.out.println(prototype != prototype2); //true
/*克隆对象与原对象的类型一样*/
System.out.println(prototype.getClass() == prototype2.getClass()); //true
}
}