Java设计模式(四):原型模式深拷贝的两种实现方式,以及和new对象的性能测试对比

来源:互联网 发布:学淘宝美工需要多少钱 编辑:程序博客网 时间:2024/05/17 08:54

本文模拟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!



0 0
原创粉丝点击