您的位置:首页 > 其它

原型模式的浅度克隆和深度克隆的实现

2015-07-15 12:16 453 查看
package com.lovo.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;

import java.util.Date;

public class Person implements Cloneable,Serializable{

private int id;

private String name;

private int age;

private Date brith;

private String address;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

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 Date getBrith() {

return brith;

}

public void setBrith(Date brith) {

this.brith = brith;

}

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

@Override

public String toString() {

return "Person [id=" + id + ", name=" + name + ", age=" + age

+ ", brith=" + brith + ", address=" + address + "]";

}

/**

* 浅克隆

*

* @return

* @throws CloneNotSupportedException

*/

public Person myclone()throws CloneNotSupportedException{

return (Person) super.clone();

}

/**

* 深克隆

* @return

* @throws CloneNotSupportedException

* @throws IOException

* @throws ClassNotFoundException

*/

public Person deepclone()throws CloneNotSupportedException, IOException, ClassNotFoundException{

ByteArrayOutputStream bos = new ByteArrayOutputStream();

ObjectOutputStream oos = new ObjectOutputStream(bos);

oos.writeObject(this);

ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());

ObjectInputStream ois = new ObjectInputStream(bis);

Person p = (Person) ois.readObject();

return p;

}

}

*********************************** 测试 ***********************************

package com.lovo.prototype;

import java.io.IOException;

import java.util.Date;

public class Test {

public static void main(String[] args) throws CloneNotSupportedException, IOException, ClassNotFoundException {

Person p = new Person();

p.setId(1);

p.setName("张三");

p.setAge(18);

p.setBrith(new Date());

p.setAddress("四川省成都市武侯区");

Person p2 = p.deepclone();

p2.setName("李四");

p2.setAge(20);

System.out.println(p);

System.out.println("**************************************************");

System.out.println(p2);

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: