• 设计模式——原型模式


    //深浅复制

    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();
             }
            
         }
    }

  • 相关阅读:
    EF框架学习
    JS DOM---Chapter 1-4
    ASP.NET页面运行机制以及请求处理流程
    cookie 与 session
    C#中的委托delegate 与 事件 event
    【转】属性与字段的区别
    使用InternalsVisibleTo给assembly添加“友元assembly”
    SQL Server 常用函数和日期操作
    C#中的get 和 set方法
    清晰易懂的Numpy入门教程
  • 原文地址:https://www.cnblogs.com/macro-renzhansheng/p/12568506.html
Copyright © 2020-2023  润新知