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

原文地址:https://www.cnblogs.com/jentary/p/5906901.html