zoukankan      html  css  js  c++  java
  • java设计模式--原型模式

    原型模式就是克隆该对象,而不是重复的new新对象(自己的理解)和javascript里原型是一个道理的。

    原型模式的 对象必须实现Cloneable接口,而Cloneable只是一个空接口,这是一种规范,如果不实现会抛CloneNotSupportedException异常,真正调用的是Object里的clone()。

    public class Sheep implements Cloneable,Serializable{
        
        private static final long serialVersionUID = 1L;
    
        private String name;
        
        private Date date;
        
        
        public Sheep(String name,Date date) {
            super();
            this.name = name;
            this.date = date;
        }
    
    
        protected Object clone() throws CloneNotSupportedException {
            Object object = super.clone();
            //深克隆
            Sheep s = (Sheep) object;
            s.date = (Date)this.date.clone();
            
            return object;
        }
        
        
        public static void main(String[] args) throws Exception {
            Sheep s1 = new Sheep("1",new Date());
            Sheep s2 = (Sheep) s1.clone();
            System.out.println(s1);
            System.out.println(s2);
            
            //序列化反序列化实现深度克隆
            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);
            Sheep s3 = (Sheep)ois.readObject();
        }
        
    
    }

     spring bean 用的就是单例和原型两种模式

  • 相关阅读:
    选择排序的C、C++实现
    冒泡排序的C、C++实现
    Node.js使用UDP通讯
    Node.js使用TCP通讯
    栈的C语言实现
    顺序表的C、C++实现
    vim的几种模式&快捷键
    ubuntu安装discourse论坛----结合在apache服务上建立虚拟主机
    Ubuntu下使用mail命令发送邮件
    深入解读EOS源代码之——区块链内核
  • 原文地址:https://www.cnblogs.com/jentary/p/5906901.html
Copyright © 2011-2022 走看看