原型模式的浅克隆和深克隆

原型模式简单说就是copy一遍实例,使用copy来的实例进行操作,而不改变原实例。涉及到浅克隆和深克隆。

1. 浅克隆:  实现Java提供的Cloneable接口。重写 Object clone方法 return super.clone();调用时就为浅克隆。

2. 深克隆: 可以使用反射进行深克隆;使用序列化进行深克隆。

  这里我演示一下序列化实现深克隆。首先,被序列化的类需要Serializable接口。我这里用了StudentDO类,在类里加上deepClone()方法。代码如下: 

    public StudentDO deepClone() {
        StudentDO student = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            student = (StudentDO) ois.readObject();
            oos.close();
            baos.close();
            ois.close();
            bais.close();
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return student;
    }

猜你喜欢

转载自www.cnblogs.com/bkxpao/p/9856410.html