原型模式
可以使用serializable接口实现对象的深复制
**************************************************
相关接口
Serializable
public interface Serializable {
}
说明:该接口为标识接口,表明实现该接口的类可被序列化
***************************************************
示例
class Address implements Serializable {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Person implements Cloneable,Serializable{
private String name;
private Integer age;
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return this.name+" "+this.age+" "+this.address+" "+super.toString();
}
@Override
protected Object clone() throws CloneNotSupportedException {
Object object=null;
try{
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream=new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(this);
ByteArrayInputStream inputStream=new ByteArrayInputStream(outputStream.toByteArray());
ObjectInputStream objectInputStream=new ObjectInputStream(inputStream);
object=objectInputStream.readObject();
}catch (Exception e){
e.printStackTrace();
}
return object;
}
}
public class MyTest {
public static void main(String[] args) throws Exception{
Address address=new Address();
address.setId(1);
address.setName("新世界");
Person person=new Person();
person.setName("瓜田李下");
person.setAge(24);
person.setAddress(address);
System.out.println(person);
Person person2=(Person)person.clone();
System.out.println(person2);
}
}
******************************************
控制台输出
瓜田李下 24 hello5.Address@49097b5d hello5.Person@2f4d3709
瓜田李下 24 hello5.Address@2b05039f hello5.Person@3d82c5f3