package com.DesignPattern.prototype;
import java.io.*;
public class Sheep implements Serializable, Cloneable {
private String name;
private int age;
private Sheep friend;
public Sheep() {
}
public Sheep(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Sheep getFriend() {
return friend;
}
public void setFriend(Sheep friend) {
this.friend = friend;
}
@Override
protected Object clone(){
Sheep sheep = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try{
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(this);
bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis);
sheep = (Sheep)ois.readObject();
}catch (Exception e){
e.printStackTrace();
}finally {
try {
bos.close();
oos.close();
bis.close();
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sheep;
}
}
使用序列化实现深拷贝
最新推荐文章于 2021-09-10 13:47:15 发布