One Day Pattern - Prototype

I. Concepts of Prototype Patterns

Prototype Pattern is used to create duplicate objects while maintaining performance.This type of design pattern is creative and provides the best way to create objects.

2. When to use the prototype mode

The prototype pattern can be understood as: using a class as a template, cloning out an infinite number of classes, the cloned classes are no longer associated with the template.

The following scenarios can use prototype mode:

  • The constructor is complex, or you don't want to use it to create objects;
  • Resource optimization, which requires more resources when a class is initialized, uses the prototype mode and clones after one initialization (no initialization anymore);
  • Performance improvements, cloning is better than creating an object with new. Cloning directly manipulates binary streams in memory, while new requires JVM to do a lot of preparation (load, validation, preparation, parsing, initialization), so it can save performance in some scenarios when creating the same objects in large quantities;

Here's a scenario of improving performance to implement the prototype pattern in Java.

3. How to use the prototype mode

3.1Implementation

First, imagine a scenario where the Mid-Autumn Festival is approaching and the system sends messages (one bar, regardless of other technology implementations) to all 5 million (or more) users, mainly to illustrate the prototype model.In this case, if you accidentally use a for loop to create 5 million objects with the new keyword, assume that a new object will cost0.04Seconds, then new5 million may not be sent in a day.

In this case, you can use the prototype pattern to improve performance, as shown in the class diagram and code below:

The code is as follows:

// Message template, inheriting Cloneable interface
public interface MessageTemplate extends Cloneable {

    // Clone message
    MessageTemplate cloneMessage() throws CloneNotSupportedException;

}

// news
public class Message implements MessageTemplate {

    // Implementing cloning methods
    public Message cloneMessage() throws CloneNotSupportedException {
        Message message;
        message = (Message) clone();
        return message;
    }

    @Override
    public String toString() {
        return "Message{" +
                "createTime=" + createTime +
                ", title='" + title + '\'' +
                ", context='" + context + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }

    // getter and setter ...

    private Date createTime;
    private String title;
    private String context;
    private String phone;


}

// Use clone mode
public class Client {

    public static void main(String[] args) throws CloneNotSupportedException {

        // Simulate sending messages, join sending 1 million messages to different users
        // Message templates use the same template, with some differences in message content
        // Then you can use the prototype pattern

        int count = 100; // No more than 1 million users
        // Create Template
        Message message = new Message();
        message.setTitle("Festival Care");
        message.setContext("Honorific%s,Hello.Come on...");
        for (int i = 0; i < count; i++) {
            Message m = message.cloneMessage();
            m.setContext(String.format(message.getContext(), i));
            m.setPhone(i + "");
            m.setCreateTime(new Date());
            System.out.println(m.toString());
        }

    }

}

// output
Message{createTime=Tue May 19 23:05:52 CST 2020, title='Festival Care', context='Dear 0, Hello.Come on...', phone='0'}
Message{createTime=Tue May 19 23:05:52 CST 2020, title='Festival Care', context='Dear 1, Hello.Come on...', phone='1'}
Message{createTime=Tue May 19 23:05:52 CST 2020, title='Festival Care', context='Dear 2, Hello.Come on...', phone='2'}
......
Message{createTime=Tue May 19 23:05:52 CST 2020, title='Festival Care', context='Dear 98, Hello.Come on...', phone='98'}
Message{createTime=Tue May 19 23:05:52 CST 2020, title='Festival Care', context='Dear 99, Hello.Come on...', phone='99'}

The code above is how the prototype pattern works and uses it.

The core is to use the clone method that comes with the Object object in Java to clone the class.

It is important to note here that the Cloneable interface, which is more specific, is not defined by the clone method, it is only used to describe objects that can use the clone method, which is a markup interface.

3.2Benefits of prototype mode

The benefits of the prototype model reflect his usage scenario:

  • The constructor is complex, or you don't want to use it to create objects;
  • Resource optimization, which requires more resources to initialize a class;
  • Performance improvements, cloning is better than creating an object with new;

3.3Matters needing attention

Two main points to note about the prototype model are:

Ignore constructors: With the clone() method, the constructor for the object is not triggered, and you need to be aware that the class needs some business in the constructor;

Deep copy: The clone() method copies the basic type, but the reference type copies the memory address (pointer) of the reference, so when clone() an object with the reference type needs to process the deep copy. There are many articles on the Internet that are not described here.

4. Summary

In general, the prototype mode is one of the simpler design modes and is better understood. It can be better applied mainly by clearing 2 points:

Use scenarios: When is it appropriate to create objects in prototype mode?

Technical implementation: involves using the cloneable interface, using the clone method of the Object object, and paying attention to the deep copy;

Above are some of my understanding of the prototype mode, there are some deficiencies, please point out, thank you.

Keywords: Java jvm

Added by scross on Tue, 19 May 2020 20:02:22 +0300