Using the serialization and deserialization deep copy is completed
ByteArrayOutputStream bos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(bos);
oos.writeObject(s1);
byte[] bytes=bos.toByteArray();
ByteArrayInputStream bis=new ByteArrayInputStream(bytes);
ObjectInputStream ois=new ObjectInputStream(bis);
Sheep3 s3=(Sheep3) ois.readObject();
Prototype Model combined with the plant model
Out of the factory model new objects can become out of Clone
Create 1000 new object Clone mode and compare mode (low configuration version)
public class Test {
public static void testNew(int size) {
long start =System.currentTimeMillis();
for(int i=0;i<size;i++) {
Iphone iphone=new Iphone();
}
long end =System.currentTimeMillis();
System.out.println("new耗时"+(end-start));
}
public static void testClone(int size) throws CloneNotSupportedException {
long start =System.currentTimeMillis();
Iphone iphone=new Iphone();
for(int i=0;i<size;i++) {
Iphone iphonex=(Iphone) iphone.clone();
}
long end =System.currentTimeMillis();
System.out.println("clone耗时"+(end-start));
}
public static void main(String[] args) throws CloneNotSupportedException {
testNew(1000);
testClone(1000);
}
}
class Iphone implements Cloneable{
public Iphone() {
try {
Thread.sleep(10);//模拟new的耗时
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Output: new time-consuming 16674
clone takes 20