JAVA design pattern -- [prototype pattern]

Posted by lookee on Thu, 28 Oct 2021 01:51:28 +0200

catalogue

Traditional way

Basic introduction to prototype mode

Source code analysis of prototype pattern in spring framework

In depth discussion - shallow discussion and deep copy

Precautions and details of prototype pattern

Traditional way

Cloned sheep problem

Now there is a sheep tom, whose name is tom, age is 1, and color is white. Please write a program to create 10 sheep with exactly the same attributes as tom sheep.
 

Traditional ways to solve the problem of cloned sheep

Train of thought analysis (illustration)

Code demonstration:

public class Sheep {
	private String name;
	private int age;
	private String color;
	public Sheep(String name, int age, String color) {
		super();
		this.name = name;
		this.age = age;
		this.color = color;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	@Override
	public String toString() {
		return "Sheep [name=" + name + ", age=" + age + ", color=" + color + "]";
	}
	
	
}
public class Client {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//traditional method 
		Sheep sheep = new Sheep("tom", 1, "white  ");
		
		Sheep sheep2 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
		Sheep sheep3 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
		Sheep sheep4 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
		Sheep sheep5 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
		//....
		
		System.out.println(sheep);
		System.out.println(sheep2);
		System.out.println(sheep3);
		System.out.println(sheep4);
		System.out.println(sheep5);
		//...
	}
}

Advantages and disadvantages of traditional methods  

① The advantages are easy to understand, simple and easy to operate.
② When creating a new object, it is always necessary to re acquire the properties of the original object. If the created object is complex, the efficiency is low. ③ it is always necessary to re initialize the object rather than dynamically obtain the running state of the object, which is not flexible enough
④ Analysis of improvement ideas  
Idea: the Object class in Java is the root class of all classes. The Object class provides a clone() method, which can copy a Java Object, but the Java class that needs to implement clone must implement an interface Cloneable, which indicates that the class can copy and has the ability to copy
 

Basic introduction to prototype mode

① Prototype pattern refers to specifying the type of objects to be created with prototype instances, and creating new objects by copying these prototypes

② Prototype pattern is a creative design pattern that allows one object to create another customizable object without knowing the details of how to create it
③ The working principle is: by passing a prototype object to the object to be created, the object to be created is created by requesting the prototype objects to copy themselves, that is, the object. clone()
④ Image understanding: Sun Dasheng pulls out monkey hair and turns into other sun Dasheng

Schematic structure diagram of prototype pattern uml diagram

Schematic structure diagram description

Prototype: a prototype class that declares an interface that clones itself
ConcretePrototype: a concrete prototype class that implements the operation of cloning itself
Client: let a prototype object clone itself to create a new object (the same properties)
 

Application of prototype pattern to solve the problem of cloned sheep
Using prototype mode to improve the traditional way, so that the program has higher efficiency and scalability.
Code demonstration:

public class Sheep implements Cloneable {
	private String name;
	private int age;
	private String color;
	private String address = "Mongolian sheep";
	public Sheep friend; //
	public Sheep(String name, int age, String color) {
		super();
		this.name = name;
		this.age = age;
		this.color = color;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	
	
	
	@Override
	public String toString() {
		return "Sheep [name=" + name + ", age=" + age + ", color=" + color + ", address=" + address + "]";
	}
	//Clone the instance using the default construction method
	@Override
	protected Object clone()  {
		
		Sheep sheep = null;
		try {
			sheep = (Sheep)super.clone();
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e.getMessage());
		}
		// TODO Auto-generated method stub
		return sheep;
	}
}
public class Client {

	public static void main(String[] args) {
		System.out.println("Prototype mode completes the creation of objects");
		// TODO Auto-generated method stub
		Sheep sheep = new Sheep("tom", 1, "white	");
		
		sheep.friend = new Sheep("jack", 2, "blue");
		
		Sheep sheep2 = (Sheep)sheep.clone(); //clone
		Sheep sheep3 = (Sheep)sheep.clone(); //clone
		Sheep sheep4 = (Sheep)sheep.clone(); //clone
		Sheep sheep5 = (Sheep)sheep.clone(); //clone
		
		System.out.println("sheep2 =" + sheep2 + "sheep2.friend=" + sheep2.friend.hashCode());
		System.out.println("sheep3 =" + sheep3 + "sheep3.friend=" + sheep3.friend.hashCode());
		System.out.println("sheep4 =" + sheep4 + "sheep4.friend=" + sheep4.friend.hashCode());
		System.out.println("sheep5 =" + sheep5 + "sheep5.friend=" + sheep5.friend.hashCode());
	}
}

Source code analysis of prototype pattern in spring framework

The creation of prototype bean s in Spring is the application of prototype patterns

In depth discussion - shallow discussion and deep copy

Basic introduction to shallow copy
① For member variables whose data type is the basic data type, shallow copy will directly transfer the value, that is, copy the attribute value to a new object.
② For a member variable whose data type is a reference data type, for example, if the member variable is an array or a class object, the shallow copy will be passed by reference, that is, only a copy of the reference value (memory address) of the member variable will be copied to the new object. Because in fact, the member variable of both objects points to the same instance. In this case, modifying the member variable in one object will affect the member variable value of another object
③ The cloned sheep in front is a shallow copy
④ Shallow copy is implemented by using the default clone() method, with sheet = (sheet) super. Clone();

Basic introduction to deep copy

① Copy the member variable values of all basic data types of the object
② Apply for storage space for all member variables of reference data type, and copy the object referenced by each member variable of reference data type until all objects reached by the object. In other words, deep copy of an object copies the entire object (including the reference type of the object)
③ Deep copy implementation method 1: rewrite the clone method to implement deep copy
④ Deep copy implementation method 2: realize deep copy through object serialization (recommended)

Deep copy application cases;

① Implement deep copy by rewriting clone method
② Deep copy using serialization
③ Code demonstration

public class DeepProtoType implements Serializable, Cloneable{
	
	public String name; //String property
	public DeepCloneableTarget deepCloneableTarget;//reference type
	public DeepProtoType() {
		super();
	}
	
	
	//Deep copy implementation method 1: rewrite the clone method to implement deep copy
	@Override
	protected Object clone() throws CloneNotSupportedException {
		
		Object deep = null;
		//Here we complete the cloning of basic data types (properties) and strings
		deep = super.clone(); 
		//The properties of reference types are processed separately
		DeepProtoType deepProtoType = (DeepProtoType)deep;
		deepProtoType.deepCloneableTarget  = (DeepCloneableTarget)deepCloneableTarget.clone();
		
		// TODO Auto-generated method stub
		return deepProtoType;
	}
	
	//Deep copy implementation method 2: realize deep copy through object serialization
	
	public Object deepClone() {
		
		//Create flow object
		ByteArrayOutputStream bos = null;
		ObjectOutputStream oos = null;
		ByteArrayInputStream bis = null;
		ObjectInputStream ois = null;
		
		try {
			
			//serialize
			bos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(bos);
			oos.writeObject(this); //Currently, this object is output as an object stream
			
			//Deserialization
			bis = new ByteArrayInputStream(bos.toByteArray());
			ois = new ObjectInputStream(bis);
			DeepProtoType copyObj = (DeepProtoType)ois.readObject();
			
			return copyObj;
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		} finally {
			//Close flow
			try {
				bos.close();
				oos.close();
				bis.close();
				ois.close();
			} catch (Exception e2) {
				// TODO: handle exception
				System.out.println(e2.getMessage());
			}
		}
		
	}
	
}
public class DeepCloneableTarget implements Serializable, Cloneable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String cloneName;

	private String cloneClass;

	//constructor 
	public DeepCloneableTarget(String cloneName, String cloneClass) {
		this.cloneName = cloneName;
		this.cloneClass = cloneClass;
	}

	//Because the properties of this class are all String, we can use the default clone here
	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}
public class Client {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		DeepProtoType p = new DeepProtoType();
		p.name = "Song Jiang";
		p.deepCloneableTarget = new DeepCloneableTarget("Daniel", "Calf class");
		
		//Method 1: complete deep copy
		
//		DeepProtoType p2 = (DeepProtoType) p.clone();
//		
//		System.out.println("p.name=" + p.name + "p.deepCloneableTarget=" + p.deepCloneableTarget.hashCode());
//		System.out.println("p2.name=" + p.name + "p2.deepCloneableTarget=" + p2.deepCloneableTarget.hashCode());
	
		//Method 2: complete deep copy
		DeepProtoType p2 = (DeepProtoType) p.deepClone();
		
		System.out.println("p.name=" + p.name + "p.deepCloneableTarget=" + p.deepCloneableTarget.hashCode());
		System.out.println("p2.name=" + p.name + "p2.deepCloneableTarget=" + p2.deepCloneableTarget.hashCode());
	
	}
}


Precautions and details of prototype pattern

① When creating a new object is complex, you can use the prototype pattern to simplify the object creation process and improve efficiency
② Instead of reinitializing the object, it dynamically obtains the running state of the object
③ If the original object changes (increase or decrease attributes), other cloned objects will also change accordingly without modifying the code
④ The implementation of deep cloning may require more complex code
⑤ Disadvantages: each class needs to be equipped with a cloning method, which is not very difficult for a new class, but when transforming an existing class, it needs to modify its source code, which violates the ocp principle. Please pay attention to this.