原型模式:用原型实例指定创建对象的类,并且通过拷贝这些原型创建新的对象。
原型模式其实就是从一个对象再创建另一个可以定制的对象,而且不需要知道锐合创建的细节。我们来看一下基本的原型模式代码
原型类:
abstract class Prototype{
private String id;
public Prototype(String id){
this.id=id;
}
public String getId(){
return id;
}
public abstract Prototype Clone();
}
具体原型类:
class ConcretePrototype1 extend Prototype{
public ConcretePrototype(String id){
super(id);
}
public Prototype Clone(){
return super.clone();
}
}
客户端代码:
static void main(String[] args){
ConcretePrototype1 p1=new ConcretePrototype1("I");
ConcretePrototype1 C2=(ConcretePrototype)p1.clone();
}
java中只要实现Cloneable接口就好,在重写一下clone方法就好了!
public class ConcretePrototype1 implements Cloneable{
@Override
public Prototype clone() {
// TODO Auto-generated method stub
Prototype pr=null;
try {
pr=(Prototype)super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pr;
}
java客户端代码;
public static void main(String[] args) {
// TODO Auto-generated method stub
ConcretePrototype1 con=new ConcretePrototype1(1);
ConcretePrototype1 con1=con.clone();
con1.setNumber(2);
System.out.println(con.getNumber());
System.out.println(con1.getNumber());
}
}
深度克隆实现:
package clonedemo;
public class Student implements Cloneable...{
private String name ;
private int age ;
teacher tea ;
Student(String name , int age,teacher tea)...{
this.name = name ;
this.age = age ;
this.tea = tea ;
}
Student()...{
}
void showInfo(String stu)...{
System.out.println(stu+ " : name ="+this.name) ;
System.out.println(stu+" : age ="+this.age) ;
System.out.println(stu+" : name ="+this.tea.getName()) ;
System.out.println(stu+" : age ="+this.tea.getAge()) ;
}
public Object clone()...{
//Object obj = null ;
Student obj = null ;
try ...{
obj = (Student)super.clone() ;
} catch (CloneNotSupportedException e) ...{
// TODO: handle exception
e.printStackTrace() ;
}
obj.tea = (teacher)tea.clone() ;
return obj ;
}
}
如果多层深度克隆就要用反射了,反射file看是不基本类,如果不是继续克隆,实际很少会用到的吧!