package com.shi.design.prototype;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* @author shiye
*
*/
public class Sleep implements Cloneable,Serializable{
private String name;
private String age;
private String add;
//对象中有一个引用对象类型的羊
private Sleep friend;
@Override
public String toString() {
return "Sleep [name=" + name + ", age=" + age + ", add=" + add + ", friend=" + friend + ", getName()="
+ getName() + ", getAge()=" + getAge() + ", getAdd()=" + getAdd() + ", getFriend()=" + getFriend()
+ ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString()
+ "]";
}
public Sleep(String name, String age, String add, Sleep friend) {
super();
this.name = name;
this.age = age;
this.add = add;
this.friend = friend;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAdd() {
return add;
}
public void setAdd(String add) {
this.add = add;
}
public Sleep getFriend() {
return friend;
}
public void setFriend(Sleep friend) {
this.friend = friend;
}
//深拷贝的俩重方式
//方式一 :使用自己重写父方法colne方法实现克隆
@Override
protected Object clone() throws CloneNotSupportedException {
Sleep sleep = (Sleep)super.clone();//实现浅拷贝
if(sleep.getFriend() != null) {
sleep.setFriend((Sleep)sleep.getFriend().clone()); //引用对象需要自己实现拷贝
}
return sleep;
}
// 方式二:通过序列化的方式实现深拷贝 (推荐使用 效率高)
public Object deepClone() {
Sleep copyObj = null;
//1 创建流对象
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try {
//2 序列化
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(this);
//3 反序列化
bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis);
copyObj = (Sleep)ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(bos != null ) {
bos.close();
}
if(oos != null ) {
oos.close();
}
if(bis != null ) {
bis.close();
}
if(ois != null ) {
ois.close();
}
} catch (IOException e2) {
e2.printStackTrace();
}
}
return copyObj;
}
}