package Prototype;
import java.io.Serializable;
import java.util.Date;
/***
* 原型模式
* @author zw
*
*/
public class Sheep1 implements Cloneable,Serializable{
private String name;
private Date birthday;
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
Object obj =super.clone();
return obj;
}
public Sheep1() {
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Sheep1(String name, Date birthday) {
super();
this.name = name;
this.birthday = birthday;
}
}
package Prototype;
import java.util.Date;
/***
* 原型模式
* @author zw
*
*/
public class Sheep2 implements Cloneable{
private String name;
private Date birthday;
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
Object obj =super.clone();
//深克隆
Sheep2 s =(Sheep2) obj;
s.birthday =(Date) this.birthday.clone();
return obj;
}
public Sheep2() {
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Sheep2(String name, Date birthday) {
super();
this.name = name;
this.birthday = birthday;
}
}
package Prototype;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
/***
* 使用序列化和反序列化
* @author zw
*
*/
public class Client3 {
public static void main(String[] args) throws Exception {
Date date = new Date(2456456456L);
Sheep1 s1 = new Sheep1("多利",date);
ByteArrayOutputStream bos =new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(s1);
byte[] data =bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(data);
ObjectInputStream ois = new ObjectInputStream(bis);
Sheep1 s2 =(Sheep1) ois.readObject();
System.out.println(s2.getName());
System.out.println(s2.getBirthday());
}
}
package Prototype;
import java.text.SimpleDateFormat;
import java.util.Date;
/***
* 测试原型模式(浅克隆)
*
* @author zw
*
*/
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
Sheep2 s1 = new Sheep2("多利",new Date(123445L));
System.out.println(s1);
System.out.println(s1.getName());
//克隆s1这只羊
Sheep2 s2 =(Sheep2) s1.clone();
System.out.println(s2);
System.out.println(s2.getName());
}
}