设计模式之GOF23原型模式02
利用序列化和反序列化完成深复制
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();
原型模式的与工厂模式相结合
工厂模式new出来的对象可以变为Clone出来的
new方式和Clone方式创建1000个对象的比较(配置低版本)
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();
}
}
输出结果:new耗时16674
clone耗时20
最新文章
- Spring类型转换 ConversionSerivce Convertor
- NoSql系列目录
- c# asp.net4.0尚未在web服务器上注册
- Magento 新增字段的值读写丢失原因
- The Swift Programming Language 中文翻译版(个人翻新随时跟新)
- AMD加载器实现笔记(三)
- 将一列包含多个ID拆分多行
- DigitalOcean上SSH Key的创建(附DigitalOcean邀请)
- java call sap
- AngularJs赋值问题
- getClass 与getSimpleName
- vvv
- mysql5.7.10和mysql5.5.39两个版本对于group by函数的处理差异
- 201521123085 《Java程序设计》 第3周学习总结
- python 3.6 MJ小工具
- gulp将多张小图自动合成雪碧图
- 【Git】(1)---工作区、暂存区、版本库、远程仓库
- python mysql数据库操作
- Set实现数组去重
- 【Python044--魔法方法:简单定制】