The Road to Java Design Patterns "Five" Prototype Patterns

Prototype

 

The idea of ​​the prototype pattern is to use an object as a prototype, copy and clone it, and generate a new object similar to the original object. In Java, copying an object is achieved through clone().

 

Very simple, a prototype class only needs to implement the Cloneable interface and override the clone method, where the clone method can be changed to any name, because the Cloneable interface is an empty interface, you can arbitrarily define the method name of the implementation class, such as cloneA or cloneB . And super.clone() calls the clone() method of Object. In the Object class, clone() is native.

 

Shallow copy: After copying an object, the variable of the basic data type will be recreated, and the reference type will still point to the original object.

Deep copy: After copying an object, whether it is a basic data type or a reference type, it is re-created. To put it simply, a deep copy is a complete copy, while a shallow copy is not complete.

 

public class Prototype implements Cloneable, Serializable {
    private static final long serialVersionUID = 1L;
    private String string;
    private SerializableObject obj;
    /* Shallow copy */
    public Object clone() throws CloneNotSupportedException {
        Prototype proto = (Prototype) super.clone();
        return proto;
    }
    /* deep copy */
      public Object deepClone() throws IOException, ClassNotFoundException {
         /* Write the current object's binary stream */   
         ByteArrayOutputStream bos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(bos);
         oos.writeObject(this);
      /* Read the new object generated by the binary stream */
      ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
      ObjectInputStream ois = new ObjectInputStream(bis);
      return ois.readObject();
    }
    public String getString() {
      return string;
    }
    public void setString(String string) {
      this.string = string;
    }
    public SerializableObject getObj() {
      return obj;
    }
    public void setObj(SerializableObject obj) {
      this.obj = obj;
    }
}
class SerializableObject implements Serializable {
    private static final long serialVersionUID = 1L;
}

 

To implement deep copying, it is necessary to read the binary input of the current object in the form of a stream, and then write out the object corresponding to the binary data.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326317207&siteId=291194637