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();
}