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 用的就是单例和原型两种模式

  • 相关阅读:
    JQuery实现页面跳转
    CSS中让背景图片居中且不平铺
    C#后台将string="23.00"转换成int类型
    BootStrap的一些基本语法
    CSS实现文字阴影的效果
    BootStrap自定义轮播图播放速度
    BootStrap 轮播插件(carousel)支持左右手势滑动的方法(三种)
    C#常用快捷键
    jQuery hover() 方法
    鼠标移动有尾巴
  • 原文地址:https://www.cnblogs.com/jentary/p/5906901.html
Copyright © 2011-2022 走看看