设计模式——原型模式
//深浅复制
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;public class Demo {
public static void main(String[] args) {
ShadowCopy shadowCopy = new ShadowCopy(1,"macro");
shadowCopy.copy();//底层看不见,但是谁调用复制谁!!
ShadowCopy shadowCopy2 = new ShadowCopy(2,"macro222");
shadowCopy2.deepCopy();//底层看不见,但是谁调用复制谁!!
}
}class ShadowCopy implements Cloneable,Serializable{
/**
*
*/
private static final long serialVersionUID = -6418640167884569655L;
private int numb;
private String name;
public ShadowCopy(int numb,String name) {
// TODO Auto-generated constructor stub
this.numb = numb;
this.name = name;
}
void copy() {
try {
ShadowCopy shadowCopy2 = (ShadowCopy) super.clone();
System.out.println(shadowCopy2.name+":"+shadowCopy2.numb);
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void deepCopy() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream outputStream = new ObjectOutputStream(bos);
outputStream.writeObject(this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
try {
ObjectInputStream ois = new ObjectInputStream(bis);
ShadowCopy shadowCopy = (ShadowCopy) ois.readObject();
System.out.println(shadowCopy.name+":"+shadowCopy.numb);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}