Definition:

Create a new object instance by copying an existing one.

Implementation:

Implement Cloneable interface:

The purpose of the Cloneable interface is to inform the virtual machine at run time that it is safe to use the Clone method on a class that implements the interface. In a Java virtual machine, only the class that implements this interface can be copied, or at run time throw CloneNotSupportedException anomalies.

Clone ();

In Java, the parent of all classes is Object, which has a Clone method that returns a copy of the Object. However, its scope is protected and ordinary classes cannot call it. Therefore, the prototype class needs to change the scope of the Clone method to public.

Example:

For example, for invitations sent by mail, most of the contents of the mail are the same: the reason for the invitation, the place to be invited, the time of gathering, etc., but the name of the invitee and the email address to be sent are different.

Define Mail class:

public class Mail implements Cloneable {    
    private String receiver;    
    private String subject;    
    private String content;    
    private String tail;    
    public Mail(EventTemplate et) {        
        this.tail = et.geteventContent();        
        this.subject = et.geteventSubject();
    }    
    @Override
    public Mail clone(a) {
        Mail mail = null;        
    try {
            mail = (Mail) super.clone();            
        } catch (CloneNotSupportedException e) {            
        // TODO Auto-generated catch block
            e.printStackTrace();
        }        return mail;
    }
/ / the get and set...
}Copy the code

Test method:

public static void main(String[] args) {
    int i = 0;
    int MAX_COUNT = 10;
    EventTemplate et = 
new EventTemplate("Invitation Letter (unchanged)"."Wedding birthday what.... (Constant part)");
    Mail mail = new Mail(et);    
    while (i < MAX_COUNT) {
        Mail cloneMail = mail.clone();
        cloneMail.setContent("Mr. (Ms.) XXX (Changing part)"
     + mail.getTail());
        cloneMail.setReceiver("Everyone's email address... Com (changing part)"); sendMail(cloneMail); i++; }}Copy the code

Advantages:

1. Using the prototype model to create an object is more efficient than simply new an object, because it directly manipulates the binary stream in memory, especially when copying large objects, the difference in performance is significant.

2. Hides the complexity of creating new instances, making creating objects as simple as copying and pasting when editing a document.

Disadvantages:

1. Since the constructor of the class will not be called when the prototype pattern is used to copy objects, the prototype pattern cannot be combined with the singleton pattern. Because the prototype class needs to change the scope of the Clone method to public type, the conditions of the singleton pattern cannot be met.

2. There can be no final objects when using the prototype pattern.

3. The Clone method of Object only copies the basic data types in the Object. For arrays and reference objects, they can only be copied separately. The concept of deep copy and shallow copy is involved here.

Deep copy and shallow copy:

Shallow copy:

When an object is copied, the variables of the base data type are recreated, and the reference type points to the same object (which is unsafe).

Deep copy:

When an object is copied, both the base data type and the reference type are recreated.

So how does deep copy work?

Continuing the example above, we add an ArrayList property.

private String receiver;
private String subject;
private String content;
private String tail;
private ArrayList<String> ars;Copy the code

Single mail = (mail) super.clone(); You cannot change the address area that ars points to, you must copy it separately:

try {
       mail = (Mail) super.clone();       
       mail.ars = (ArrayList<String>)this.ars.clone();
      } catch (CloneNotSupportedException e) {
          e.printStackTrace();
}Copy the code

Applicable scenarios:

1. Copy the structure and data of the object.

2. It is expected that modifications to the target object will not affect the existing prototype object.

3. The cost of creating an object is high.

Original: https://www.javazhiyin.com/470.html