原型模式深入--使用序列化机制实现对象的深克隆

其实对象的深克隆还可以通过序列化来实现,直接上代码,对象使用的还是之前的sheep对象,但是要实现Serializable的接口:

public class Client3 {
    public static void main(String[] args) throws CloneNotSupportedException, Exception {
        Date date = new Date(12312321331L);
        Sheep s1 = new Sheep("少利",date);
        System.out.println(s1);
        System.out.println(s1.getSname());
        System.out.println(s1.getBirthday());


//      使用序列化和反序列化实现深复制
        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 s2 = (Sheep) ois.readObject();   //克隆好的对象!

        System.out.println("修改原型对象的属性值");  
        date.setTime(23432432423L);

        System.out.println(s1.getBirthday());

        s2.setSname("多利");
        System.out.println(s2);
        System.out.println(s2.getSname());
        System.out.println(s2.getBirthday());


    }
}

你可能感兴趣的:(设计模式(Design,Pattern))