Prototype pattern of Java design pattern

Prototype pattern of Java design pattern

It's been several days. Today, I'll write about the prototype pattern in the design pattern. I've seen the sample code a few days ago. I want to do some optimization to make it easier for everyone to understand this pattern more deeply. In addition, I also need to find more detailed information

1: What is the meaning of prototype pattern?

Use prototype instances to specify the kind of objects to create, and create new objects by copying these prototypes. Prototype pattern is an object creation pattern.

2: Problems solved

Large overhead of repeated creation of multiple identical objects

3: Mode principle

3.1 structure of mode
Prototype (Abstract prototype class): it is the interface for declaring cloning methods. It is the public parent class of all concrete prototype classes. It can be an abstract class, an interface, or even a concrete implementation class.
Concreteprototype (concrete prototype class): it implements the cloning method declared in the Abstract prototype class, and returns one of its own cloned objects in the cloning method.
Client (customer class): let a Prototype object clone itself to create a new object. In the customer class, you only need to create a Prototype object directly or through factory methods. You can get multiple identical objects by calling the object cloning method. Because the client is programmed for the Abstract Prototype class Prototype, users can select specific Prototype classes according to their needs. The system has good scalability, and it is convenient to add or replace specific Prototype classes.

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:

  1. 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 runtime that the clone method can be safely used on the class that implements this interface. In the java virtual machine, only the classes that implement this interface can be copied. Otherwise, CloneNotSupportedException will be thrown at runtime.
  2. 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 is used to return a copy of the Object, but 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

IV. implementation code

Step 1: Prototype

@Data
public class MonkeySun implements Cloneable {
    private String name;
    private String weapon;

    @Override
    protected Object clone(){
        Object clone = null;
        try {
            clone = super.clone();
        } catch (CloneNotSupportedException e) {
            System.out.println("Wukong split failed");
        }
        return clone;
    }
}

Step 2: Test

public class PrototypeTest {
    public static void main(String[] args) {
        MonkeySun monkeySun = new MonkeySun();
        monkeySun.setName("Sun WuKong");
        monkeySun.setWeapon("Golden cudgel");
        System.out.println("prototype : " + monkeySun + " hashcode : " +monkeySun.hashCode());

        MonkeySun clone = (MonkeySun) monkeySun.clone();
        clone.setName("Monkey King");
        clone.setWeapon("Yin Yang bottle");
        System.out.println("clone : " + clone + " hashcode : " +clone.hashCode());

    }


Clone the resulting new object
Below, Sun Wukong learned a new skill Disha 72 change
Wukong entity:

@Data
public class MonkeySun implements Serializable,Cloneable {
    private String name;
    private String weapon;
    private Magic magic;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

Supernatural powers:

@Data
public class Magic{
    private String name;

    public Magic() {
    }

    public Magic(String name) {
        this.name = name;
    }
}

practice:

MonkeySun monkeySun = new MonkeySun();
        monkeySun.setMagic(new Magic("Three head malpractice"));
        monkeySun.setName("Sun WuKong");
        monkeySun.setWeapon("Golden cudgel");
        System.out.println("prototype : " + monkeySun + monkeySun.hashCode());

        MonkeySun clone = (MonkeySun) monkeySun.clone();
        System.out.println("clone : " + clone + clone.hashCode());


        monkeySun.getMagic().setName("Disha 72 change");
        System.out.println("prototype : " + monkeySun + monkeySun.hashCode());
        System.out.println("clone : " + clone + clone.hashCode());

Test:

prototype : MonkeySun(name=Sun WuKong, weapon=Golden cudgel, magic=Magic(name=Three head malpractice))-2098436648
 clone : MonkeySun(name=Sun WuKong, weapon=Golden cudgel, magic=Magic(name=Three head malpractice))-2098436648
 prototype : MonkeySun(name=Sun WuKong, weapon=Golden cudgel, magic=Magic(name=Disha 72 change))-2015179652
 clone : MonkeySun(name=Sun WuKong, weapon=Golden cudgel, magic=Magic(name=Disha 72 change))-2015179652

A strange thing happened. Wukong's prototype learned 72 changes, and his separation naturally learned. In fact, there is no such bug. The prototype changes. The cloned object should be an independent individual and does not involve change Therefore, a concept of prototype pattern, shallow cloning, is introduced
Shallow cloning: create a new object. The properties of the new object are exactly the same as the original object. For non basic type properties, it still points to the memory address of the object pointed to by the original property.
Deep clone: when a new object is created, other objects referenced in the attribute will also be cloned and no longer point to the original object address.
So how to achieve deep cloning to achieve this independence?
The answer is very simple. The sub object also implements the relevant interface of clone, and the prototype class increases the return of the object

@Data
public class Magic implements Cloneable{
    private String name;

    public Magic() {
    }

    public Magic(String name) {
        this.name = name;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

Prototype object return:

@Data
public class MonkeySun implements Cloneable {
    private String name;
    private String weapon;
    private Magic magic;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        MonkeySun monkeySun = (MonkeySun)super.clone();
        monkeySun.magic = (Magic) this.magic.clone();
        return monkeySun;
    }
}

Test:

 public static void main(String[] args) throws CloneNotSupportedException {
        MonkeySun monkeySun = new MonkeySun();
        monkeySun.setMagic(new Magic("Three head malpractice"));
        monkeySun.setName("Sun WuKong");
        monkeySun.setWeapon("Golden cudgel");
        System.out.println("prototype : " + monkeySun + monkeySun.hashCode());

        MonkeySun clone = (MonkeySun) monkeySun.clone();
        System.out.println("clone : " + clone + clone.hashCode());


        monkeySun.getMagic().setName("Disha 72 change");
        System.out.println("prototype : " + monkeySun + monkeySun.hashCode());
        System.out.println("clone : " + clone + clone.hashCode());

    }

Result display:

prototype : MonkeySun(name=Sun WuKong, weapon=Golden cudgel, magic=Magic(name=Three head malpractice))-2098436648
 clone : MonkeySun(name=Sun WuKong, weapon=Golden cudgel, magic=Magic(name=Three head malpractice))-2098436648
 prototype : MonkeySun(name=Sun WuKong, weapon=Golden cudgel, magic=Magic(name=Disha 72 change))-2015179652
 clone : MonkeySun(name=Sun WuKong, weapon=Golden cudgel, magic=Magic(name=Three head malpractice))-2098436648

In addition, deep cloning is realized through serialization. If you want to know, you can learn about it through other ways

V. summary:

Application scenario:
There are not many separate application scenarios of prototype mode, which are generally used together with other actual modes

There are so many records about the study of prototype mode. If it is helpful to you, you can click a zanha. Your encouragement is also the driving force of creation Come on in the computer world!

Keywords: Java Design Pattern

Added by dbrimlow on Tue, 01 Feb 2022 23:33:15 +0200