分为三部分:原型类,原型子类,调用类
原型类:
public class Prototype implements Cloneable{
public Prototype clone(){
Prototype prototype = null;
try {
prototype = (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return prototype;
}
}
原型子类:
public class ConcretePrototype extends Prototype {
public void show(){
System.out.println("这是一个原型");
}
}
调用类:
public class Test {
public static void main(String[] args){
ConcretePrototype cp = new ConcretePrototype();
cp.show();
ConcretePrototype clone = (ConcretePrototype)cp.clone();
clone.show();
}
}
Cloneable接口是在运行时,通知虚拟机能够安全的使用clone方法(object中clone方法,所以所有类继承了,但是是protect,所以需要修改为public)。如果没有,则会报错java.lang.CloneNotSupportedException。
clone方法只会拷贝java的基本数据类型:byte,short,int,long,float,double,char,boolean,其他的数据类型需要用户手动拷贝,例如:
public class Prototype implements Cloneable{
public ArrayList<String> list = new ArrayList<String>();
public Prototype clone(){
Prototype prototype = null;
try {
prototype = (Prototype) super.clone();
prototype.list = (ArrayList<String>) this.list.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return prototype;
}
}
假如不这样做,新clone的对象会对这些数据类型进行引用,这是不安全的。
clone是直接在内存中进行复制,所以类的构造方法是不会调用的,访问权限也无用,特别需要注意此点。例如单例模式,与此模式是冲突的。