本文模擬Laptop類的創建過程很耗時,在構造器裏休眠了10毫秒。
package com.iter.devbox.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;
public class Client2 {
private static void test01(int size) {
long begin = System.currentTimeMillis();
for (int i = 0; i < size; i++) {
Laptop obj = new Laptop();
}
long end = System.currentTimeMillis();
System.out.println("new的方式創建對象耗時:" + (end - begin));
}
private static void test02(int size) {
long begin = System.currentTimeMillis();
Laptop obj = new Laptop();
for (int i = 0; i < size; i++) {
Laptop obj1 = (Laptop) obj.clone();
}
long end = System.currentTimeMillis();
System.out.println("clone的方式創建對象耗時:" + (end - begin));
}
private static void test03(int size) {
long begin = System.currentTimeMillis();
Laptop obj = new Laptop();
for (int i = 0; i < size; i++) {
Laptop obj1 = (Laptop) obj.deepClone();
}
long end = System.currentTimeMillis();
System.out.println("序列化的方式創建對象耗時:" + (end - begin));
}
public static void main(String[] args) {
test01(100);
test02(100);
test03(100);
}
}
//筆記本電腦
class Laptop implements Cloneable,Serializable{
public Laptop() {
try {
Thread.sleep(10); //模擬創建對象很耗時
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//利用Object的clone()方法實現深拷貝
protected Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
//利用序列號和反序列化實現深拷貝
public Object deepClone() {
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
return oi.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
}
new的方式創建對象耗時:1001
clone的方式創建對象耗時:10
序列化的方式創建對象耗時:54
測試結論:
如果需要短時間創建大量對象,並且new的過程比較耗時,則可以考慮使用原型模式。
而採用clone的方式,相比序列號的方式,更高效。只不過,如果類中有成員變量是引用類型,也要一起進行clone!