Explain the prototype pattern in Java design pattern programming in detail
Definition: specify the type of objects to be created with prototype instances, and create new objects by copying these prototypes. Type: create class schema class diagram:
Prototype pattern is mainly used for object replication. Its core is the prototype class prototype in the class diagram. Prototype class needs to meet the following two conditions: implement clonable interface. There is a clonable interface in the Java language, which has only one function, that is, to inform the virtual machine at run time that the clone method can be safely used on the class that implements this interface. In the Java virtual machine, only classes that implement this interface can be copied. Otherwise, clonenotsupportedexception will be thrown at runtime. Override the clone method in the object class. In Java, the parent class of all classes is the object class. There is a clone method in the object class, which returns a copy of the object. However, its scope is of protected type, and ordinary classes cannot call it. Therefore, the prototype class needs to modify the scope of the clone method to public type. Prototype pattern is a relatively simple pattern, which is also very easy to understand. Implementing an interface and rewriting a method completes the prototype pattern. In practical applications, prototype patterns rarely appear alone. It is often mixed with other patterns, and its prototype class prototype is often replaced by abstract classes. Implementation code:
client:
Advantages and applicable scenarios using prototype mode to create an object is much better in performance than directly new an object, because the clone method of object class is a local method, which directly operates the binary stream in memory, especially when copying large objects. Another advantage of using prototype mode is to simplify the creation of objects, making the creation of objects as simple as copy and paste when editing documents. Because of the above advantages, you can consider using the prototype pattern when you need to create similar objects repeatedly. For example, you need to create objects in a loop. If the object creation process is complex or there are many cycles, using the prototype mode can not only simplify the creation process, but also improve the overall performance of the system.
Precautions for prototype mode:
Because ArrayList is not a basic type, the member variable list will not be copied. We need to implement a deep copy ourselves. Fortunately, most container classes provided by Java implement the clonable interface. Therefore, it is not particularly difficult to implement deep copy. PS: in the deep copy and shallow copy problems, there are 8 basic types and their encapsulation types in Java, as well as string types. The rest are shallow copies.