码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式——原型模式

时间:2020-03-25 19:18:37      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:out   clone   name   stat   you   system   ace   看不见   put   

//深浅复制

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Demo {
     public static void main(String[] args) {
         ShadowCopy shadowCopy = new ShadowCopy(1,"macro");
         shadowCopy.copy();//底层看不见,但是谁调用复制谁!!
        
         ShadowCopy shadowCopy2 = new ShadowCopy(2,"macro222");
         shadowCopy2.deepCopy();//底层看不见,但是谁调用复制谁!!
     }
}

class ShadowCopy implements Cloneable,Serializable{
    
     /**
      *
      */
     private static final long serialVersionUID = -6418640167884569655L;
     private int numb;
     private String name;
     public ShadowCopy(int numb,String name) {
         // TODO Auto-generated constructor stub
         this.numb = numb;
         this.name = name;
     }
     void copy() {
         try {
             ShadowCopy shadowCopy2 = (ShadowCopy) super.clone();
             System.out.println(shadowCopy2.name+":"+shadowCopy2.numb);
         } catch (CloneNotSupportedException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
    
     void deepCopy() {
         ByteArrayOutputStream bos = new ByteArrayOutputStream();
         try {
             ObjectOutputStream outputStream = new ObjectOutputStream(bos);
             outputStream.writeObject(this);
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
        
         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
         try {
             ObjectInputStream ois = new ObjectInputStream(bis);
             ShadowCopy shadowCopy = (ShadowCopy) ois.readObject();
             System.out.println(shadowCopy.name+":"+shadowCopy.numb);
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         } catch (ClassNotFoundException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
        
     }
}

设计模式——原型模式

标签:out   clone   name   stat   you   system   ace   看不见   put   

原文地址:https://www.cnblogs.com/macro-renzhansheng/p/12568506.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!