Prototype Pattern

本文介绍了两种实现原型模式的方法:通过序列化和反序列化实现深拷贝,以及通过实现Cloneable接口进行浅拷贝。深拷贝能创建完全独立的对象副本,包括所有子对象,而浅拷贝仅复制对象本身,不复制引用的子对象。这两种策略在复杂对象创建时尤为有用。
摘要由CSDN通过智能技术生成

Prototype Pattern can help create multiple objects when creation process is complicated, 2 ways to implement it.

Way1 (recommended):

Implement interface Serializable, serializate current object then deserializate it to return new object, all parameters and child object instances will be re-created, it's deep copy approach.

​// Deep clone approach - recommended
public DeepcloneObject deepClone() {

    ByteArrayOutputStream bos = null;
    ByteArrayInputStream bis = null;
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;

    try {
        // Serialization
        bos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(bos);
        oos.writeObject(this);

        // Deserialization
        bis = new ByteArrayInputStream(bos.toByteArray());
        ois = new ObjectInputStream(bis);
        DeepcloneObject deepCloneObj = (DeepcloneObject) ois.readObject();

        return deepCloneObj;

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            bos.close();
            bis.close();
            ois.close();
            oos.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Way2:

Implement interface Cloneable, override object's clone method, all underlying objects need to clone and assign to new object to implement deep copy approach, otherwise just use object's clone method to return new object as shallow copy approach.

  • Deep copy approach
// Deep clone approach
@Override
public Object clone() throws CloneNotSupportedException {
    DeepCloneObject deepCloneObject = (DeepCloneObject) super.clone();
    DeepCloneObject target = deepCloneObject;
    Subclass child = (Subclass) deepCloneObject.getChild().clone();
    target.child = child;
    return target;
}
  • Shallow copy approach
// Shallow clone approach
@Override
public Object clone() throws CloneNotSupportedException {
    return super.clone();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值