Prototype pattern of design pattern
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 requires the following two conditions:
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:
Advantages and applicable scenarios of prototype mode
The performance of using prototype mode to create an object is much better 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.