preface

The stereotype pattern belongs to the object creation pattern. Specify the types of all created objects by giving a prototype object, and then create more objects of the same type using the copy method provided by the prototype object.

The structure of the prototype pattern

The prototype pattern requires an object to implement an interface (type) that can clone itself. In this way, creating a new object from a prototype instance does not need to care about the type of the instance itself, just implement the method of cloning itself, and do not need to create it through new.

Representation of a stereotype type

  1. Simple form
  2. The registration form

The body of the

Simple form

The role of

  1. Client role: The Client class makes a request to create an object.
  2. Prototype Role: This is an abstract role, usually composed of oneJavainterfaceorJavaAn abstract classThe implementation. This role defines the methods required to implement the concrete stereotype class.
  3. Concrete Prototype role: This role needs to implement the clon-related interfaces required by the abstract Prototype role.

The sample code

Prototype.java

/** * Abstract prototype role */
public abstract class Prototype {
    private String id;

    public Prototype(String id) {
        this.id = id;
    }

    public String getId(a) {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    /** * A way to clone yourself *@returnAn object cloned from itself. * /
    public abstract Prototype clone(a);
}
Copy the code

ConcretePrototype1.java

public class ConcretePrototype1 extends Prototype {
    public ConcretePrototype1(String id) {
        super(id);
    }

    public Prototype clone(a) {
        Prototype prototype = new ConcretePrototype1(this.getId());
        returnprototype; }}Copy the code

ConcretePrototype2.java

public class ConcretePrototype2 extends Prototype {
    public ConcretePrototype2(String id) {
        super(id);
    }

    public Prototype clone(a) {
        Prototype prototype = new ConcretePrototype2(this.getId());
        returnprototype; }}Copy the code

The results

The registration form

The role of

  1. Client role: The Client class makes a request to create an object.
  2. Prototype Role: This is an abstract role, usually composed of oneJavainterfaceorJavaAn abstract classThe implementation. This role defines the methods required to implement the concrete stereotype class.
  3. Concrete Prototype role: This role needs to implement the clon-related interfaces required by the abstract Prototype role.
  4. Prototype Manager role: Provides creation and management of various Prototype objects.

The sample code

There is no difference between the registry mode and the simple mode, except for the Prototype Manager.

Prototype.java W

public interface Prototype {
    public Prototype clone(a);
    public String getName(a);
    public void setName(String name);
}
Copy the code

ConcretePrototype1.java

public class ConcretePrototype1 implements Prototype {
    private String name;

    @Override
    public String getName(a) {
        return this.name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public Prototype clone(a) {
        Prototype prototype = new ConcretePrototype1();
        prototype.setName(this.name);
        return prototype;
    }

    @Override
    public String toString(a) {
        return "ConcretePrototype1 [name=" + name + "]"; }}Copy the code

ConcretePrototype2.java

public class ConcretePrototype2 implements Prototype {
    private String name;

    @Override
    public String getName(a) {
        return this.name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public Prototype clone(a) {
        Prototype prototype = new ConcretePrototype2();
        prototype.setName(this.name);
        return prototype;
    }

    @Override
    public String toString(a) {
        return "ConcretePrototype2 [name=" + name + "]"; }}Copy the code

PrototypeManager.java

public class PrototypeManager {
    /** * the object relationship between the prototype number and the prototype instance */
    private static Map<String, Prototype> map = new HashMap<>();

    /** * privatize the constructor to avoid creating instances */ from outside
    private PrototypeManager(a) {}/** * Add or modify the prototype instance to the prototype manager **@paramPrototypeId prototypeId *@paramPrototype Prototype */
    public static void setProtoType(String prototypeId, Prototype prototype) {
        map.put(prototypeId, prototype);
    }

    /** * Removes the prototype instance from the prototype manager based on the prototype number **@paramPrototypeId prototypeId */
    public static void removePrototype(String prototypeId) {
        map.remove(prototypeId);
    }

    /** * Get the prototype instance from the prototype number **@paramPrototypeId prototypeId *@returnPrototype instance object *@throwsException If an instance cannot be obtained based on the stereotype number, the Exception "the stereotype you want to obtain is not registered or has been destroyed" */ is displayed
    public static Prototype getPrototype(String prototypeId) throws Exception {
        Prototype prototype = map.get(prototypeId);

        if (prototype == null) {
            throw new Exception("The prototype you wish to obtain has not been registered or destroyed.");
        }

        returnprototype; }}Copy the code

Client.java

public class Client {
    public static void main(String[] args) {
        try {
            // Create the first instance
            Prototype p1 = new ConcretePrototype1();
            // Register the first instance
            PrototypeManager.setProtoType("p1", p1);

            // Clone the prototype of the first instance
            Prototype p3 = PrototypeManager.getPrototype("p1").clone();
            p3.setName("Zhang");
            System.out.println("Copy of first instance:" + p3);

            // Create a second instance
            Prototype p2 = new ConcretePrototype2();
            // Register the second instance
            PrototypeManager.setProtoType("p2", p2);

            // Clone the prototype of the second instance
            Prototype p4 = PrototypeManager.getPrototype("p2").clone();
            p4.setName("Bill");
            System.out.println("Copy of second instance:" + p4);

            // Unregister the first instance
            PrototypeManager.removePrototype("p1");
            // Clone the prototype of the first instance again
            Prototype p5 = PrototypeManager.getPrototype("p1").clone();
            p5.setName("Fifty");
            System.out.println("Copy of first instance:" + p5);
        } catch(Exception e) { e.printStackTrace(); }}}Copy the code

The results

The comparison between the two

Both the simple and registry archetypal patterns have their strengths and weaknesses.

  1. You can use the first form if you want to create a prototype object that has less data and is relatively fixed. In this case, the reference to the prototype object can be saved by the client itself.
  2. The second form can be used if the prototype object to be created is not fixed in data. In this case, the client does not save a reference to the stereotype object, and the task is delegated to the stereotype manager role. Before cloning an object, the client can check to see if the administrator object already has a prototype object that meets the requirements. If so, you can get the object reference from the stereotype manager role; If not, the client needs to copy the prototype object itself.

conclusion

Advantages of the prototype pattern

The prototype pattern allows specific implementation types to be dynamically changed at run time. The prototype pattern allows a client to register an implementation type that matches the prototype interface at runtime, or to dynamically change the specific implementation type so that the interface doesn’t appear to have changed at all, but is actually running another class entity. Because cloning a prototype object is similar to instantiating a class.

Disadvantages of the prototype pattern

The main drawback of the prototype pattern is that each class must be equipped with a clone method. Deploying cloning requires a thorough consideration of the functionality of a class, which is not difficult for a brand new class, but not easy for an existing class.


Welcome to pay attention to the technical public number: Zero one Technology Stack

This account will continue to share learning materials and articles on back-end technologies, including virtual machine basics, multithreaded programming, high-performance frameworks, asynchronous, caching and messaging middleware, distributed and microservices, architecture learning and progression.