Design Pattern-Prototype mode

Source: Internet
Author: User
1. Prototype pattern definition

The prototype pattern is very simple and is defined as follows:

Specify the kind of objects created with the prototype instance and create new objects by copying the prototypes

2. General class Diagram

The core of the prototype pattern is the implementation of the Cloneable interface, which is an identity interface provided by the JDK, and only classes that implement this interface can be copied.
The generic class diagram of the prototype pattern is as follows;

3. Generic prototype Implementation code

Prototype class:

public class ConcretePrototype implements Cloneable {    private int id;    private String name;    public ConcretePrototype() {        System.out.println("ConcretePrototype construct.");    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    @Override    protected Object clone() throws CloneNotSupportedException {        ConcretePrototype concretePrototype = null;        try {            concretePrototype = (ConcretePrototype) super.clone();        } catch (Exception e) {        }        return concretePrototype;    }    @Override    public String toString() {        return "ConcretePrototype{" +                "id=" + id +                ", name='" + name + '\'' +                '}';    }}

Client Test Code:

public class Client {    public static void main(String[] args) throws Exception {        ConcretePrototype concretePrototype = new ConcretePrototype();        concretePrototype.setId(123);        concretePrototype.setName("test");        ConcretePrototype cloneType = (ConcretePrototype) concretePrototype.clone();        cloneType.setId(111);        cloneType.setName("test111");        System.out.println(concretePrototype);        System.out.println(cloneType);    }}

The output results are as follows:

ConcretePrototype construct.ConcretePrototype{id=123, name='test'}ConcretePrototype{id=111, name='test111'}

It can be seen from the output that a new object is copied through the Clone method.

4. Advantages of prototype mode

1. Excellent performance
The prototype pattern is a copy of the binary stream in memory, much faster than a direct new object.

2. With the output from 3, the constructor does not execute at the Clone object, which may be called a constraint for some classes that need to be initialized in the constructor

5. Points to be aware of

You need to be aware of the properties of a mutable reference type when copying in prototype mode, and here is an example to illustrate this problem:
Copy objects:

public class DeepClone implements Cloneable{    private Map<String, Object> map = new HashMap<>();    public void addPair(String key, String value){        map.put(key, value);    }    public Map<String , Object> getMap(){        return map;    }    @Override    protected Object clone() throws CloneNotSupportedException {        DeepClone  deepClone = null;        try {            deepClone = (DeepClone) super.clone();        } catch (Exception e) {        }        return deepClone;    }}

Client class

public class Client {    public static void main(String[] args) throws Exception {        DeepClone deepClone = new DeepClone();        deepClone.addPair("key1", "value1");        DeepClone clone = (DeepClone) deepClone.clone();        clone.addPair("key2", "value2");        System.out.println(deepClone.getMap());    }}

The output results are as follows:

{key1=value1, key2=value2}

When copying an object using the Clone method, the property of the reference type does not continue to copy, but multiple copy objects use the same property, which is called a shallow copy.
The following is a deep copy of the Clone method rewrite complete:

@Overrideprotected Object clone() throws CloneNotSupportedException {    DeepClone  deepClone = null;    try {        deepClone = (DeepClone) super.clone();        Map<String, Object> cloneMap = new HashMap<>();        cloneMap.putAll(this.map);        deepClone.map = cloneMap;    } catch (Exception e) {    }    return deepClone;}

The re-execution of the client output results in:

{key1=value1}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.