For a detailed explanation of the “prototype pattern,” see my blog

Design patterns part 2 creative design patterns chapter 6 prototype patterns (A: C++ implementation)

This article is a Java implementation of the “prototype pattern”.

The clone in prototype mode is divided into shallow clone and deep clone. The Object class in Java provides the clone() method of shallow clone. The concrete prototype class can realize shallow clone as long as it implements the Cloneable interface, which is the abstract prototype class. The code is as follows:

Step 1: Concrete prototype classes

package com;

public class ConcretePrototype implements Cloneable{

	public ConcretePrototype(a)
	{
		System.out.println("Concrete prototype created successfully!");
	}
	
    public Object clone(a) throws CloneNotSupportedException
    {
        System.out.println("Concrete prototype copied successfully!");
        return (ConcretePrototype)super.clone(); }}Copy the code

Step 2: Test

package com;

public class Main {

	public static void main(String[] args) throws CloneNotSupportedException {
		
		ConcretePrototype obj1= new ConcretePrototype();
		ConcretePrototype obj2 = (ConcretePrototype)obj1.clone();
		
		System.out.println("obj1==obj2? "+ (obj1==obj2)); }}Copy the code

The result is as follows:



To further illustrate, let me give you another example. The “three good student” certificate of the same school besides the name of the winner is different, the other are the same, belong to the copy of similar object, can also be created with the prototype model, and then make simple modification is ok. FIG. 3 shows the structure of merit student certificate generator.

FIG. 1 Structure diagram of the award generator

The code looks like this:

Citation.java

package com;

public class Citation implements Cloneable{
    
	String name;
    String info;
    String college;
    Citation(String name,String info,String college)
    {
        this.name=name;
        this.info=info;
        this.college=college;
        System.out.println("Certificate created successfully!");
    }
    void setName(String name)
    {
        this.name=name;
    }
    String getName(a)
    {
        return(this.name);
    }
    void display(a)
    {
        System.out.println(name+info+college);
    }
    public Object clone(a) throws CloneNotSupportedException
    {
        System.out.println("Certificate copied successfully!");
        return (Citation)super.clone(); }}Copy the code

Main.java

package com;

public class Main {

	public static void main(String[] args) throws CloneNotSupportedException {
		
        Citation obj1=new Citation("Zhang".Student: I performed well in the first semester of the 2016 academic year and was awarded "Merit Student".."Shaoguan College");
        obj1.display();
        Citation obj2=(Citation) obj1.clone();
        obj2.setName("Bill"); obj2.display(); }}Copy the code