Vernacular prototype model (Prototype Pattern)

intention

Prototype model is to create a design mode, you can copy existing objects without relying on its class.

problem

If you now have an object, we would like to complete a copy of the new, how do we do?

  1. Create a new object of the same class
  2. Through all the values ​​of an existing object, then copy their value into the new object.

Good, but we will find the following problems:

  1. The value of this object is not necessarily all of the outside world, such as Java in private, outside inaccessible.
  2. Using this approach must know the class of the object belongs and rely on this class.
  3. Sometimes we only know that the object implements the interface, rather than a specific category.

solve

This time we need a prototype model. Prototype mode cloning delegated to the object to be cloned. This mode supports all clones object declaration a common interface that allows cloning of an object, the coupling will not class code and the object. Typically, such an interface only comprises a cloning method.

Implemented cloning method are very similar in all classes. This method creates an object of the current class, and transfer all field values ​​of the old object to the new object. So that you can copy the private field, because most programming languages ​​allow object access private fields belonging to the same class.

structure

FIG class prototype model

Prototype model contains the following roles

  • Prototype: It is the interface declarations cloning process, all of the specific public prototype parent class, an abstract class may be an interface, it can even be embodied class.
  • ConcretePrototype: It implements cloning methods declared in the abstract class prototype, a clone back to their cloning process

Examples

In Java, all classes inherit java.lang.Object. Object clone provides a method to achieve Java object replication.
We just need to pay attention to two points.

  1. Achieve cloning Java class must implement a marker interface Cloneable, expressed support for the Java class is copied. If you do not implement this interface method calls but the clone (), Java compiler will throw a CloneNotSupportedException exception.
  2. Shallow and deep cloning clone
    of java clone function only "shallow clone", that is, only the variable values do replication. If the variable is referenced, the contents at the memory address is unchanged.

references

https://refactoring.guru/design-patterns/prototype

Guess you like

Origin www.cnblogs.com/zcr3108346262/p/12209384.html