原型模式
- 原始方法
public class Sheep{
private String name;
private int age;
prrivate String color;
public Sheep(String name,int age,String color){
this.name = name;
this.age = age;
this.color = color;
}
//set get 方法
}
public class Client{
public static void main(String[] agrs){
Sheep sheep - new Sheep("xx",1,"xx");
//传统方法
Sheep sheep1 - new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
Sheep sheep2 - new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
Sheep sheep3 - new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
Sheep sheep4 - new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
Sheep sheep5 - new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
}
}
改进
public class Sheep{
private String name;
private int age;
private String color;
public Sheep(String name,int age,String color){
this.name = name;
this.age = age;
this.color = color;
}
//set get 方法
//克隆该实例,使用默认的clone方法
protected Object clone() {
Sheep sheep = null;
try{
sheep = (Sheep)super.clone();
}catch(Exception ex){
System.out.println(ex.getMessage());
}
return sheep;
}
}
public class Client{
public static void main(String[] agrs){
Sheep sheep - new Sheep("xx",1,"xx");
//传统方法
Sheep sheep1 - sheep.clone();
Sheep sheep2 - sheep.clone();
Sheep sheep3 - sheep.clone();
Sheep sheep4 - sheep.clone();
Sheep sheep5 - sheep.clone();
Sheep sheep6 - sheep.clone();
}
}
深拷贝
public class DeepCloneableTarget implements Serializable,Cloneable{
private static final long serialVersionUID = 1L;
private Stirng cloneName;
private String cloneClass;
public DeepCloneableTarget(String cloneName,String cloneClass){
this.cloneName = cloneName;
this.cloneClass = cloneClass;
}
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
}
public class DeepProtoType implements Serializable,Cloneable{
public String name;
public DeepCloneableTarget deepCloneableTarget;
public DeepProtoType(){
super();
}
//深拷贝(方法一) 使用clone方法
public Object clone() throws CloneNotSupportedException{
Object deep = null;
//先完成基本数据类型的克隆
deep = super.clone();
//对引用数据类型的属性进行处理
DeepProtoType deepProtoType = (DeepProtoType)deep;
deepProtoType.deepCloneableTarget = (DeepCloneableTarget)deepCloneableTarget.clone();
return deep;
}
//深拷贝(方法二) 通过对象的序列化
public Object deepClone(){
//创建流对象
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bis - null;
ObjectInputStream ois = null;
try{
// 序列化
bos = new ByetArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(this);//当前对象以输出流方式输出
//反序列化
bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ByteArrayInputStream(bis);
DeepProtoType copyObj = (DeepProtoType)ois.readObject();
return copyObj;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
try{
bos.close();
oos.close();
bis.close();
ois.close();
}catch(Exception e2){
e2.printStackTrace();
}
}
}
}