zoukankan      html  css  js  c++  java
  • 设计模式之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

  • 相关阅读:
    Windows CE下拨号上网
    JS验证示例
    Automation server can't create object , AUTOMATION服务器无法创建对象
    使用企业库调用存储过程(带参数)完成数据获取样例
    hibernate 一对多 多对一 关系表 增删改查大礼包ps二级查也有
    游戏服务器架构
    游戏中的加密算法
    二进制高效位运算
    游戏网络知识
    复习hiernate
  • 原文地址:https://www.cnblogs.com/code-fun/p/11329920.html
Copyright © 2011-2022 走看看