One , Basic introduction

prototype (Prototype) Pattern is an object creation pattern , He creates instances of objects by copying prototype objects . Instances created using prototype patterns , Has the same data as the prototype .

The implementation of prototype pattern is mainly based on the sun The cloning mechanism provided by the company , stay Object There is one in this class clone method , This method uses protected Method modified , All ordinary java If a class wants to be clonal, it has to override this clone method , We can encapsulate this method into an abstract class , If you want to be able to clone, inherit this abstract class Cloneable.

Two , Characteristics of prototype mode

1, The target object is created by the prototype object itself . in other words , The action of object creation comes from the prototype object itself .

2, The target object is a clone of the prototype object . in other words , Objects created through prototype patterns , It's not just the same structure as the prototype object , It also has the same value as the prototype object .

3, According to the different levels of object cloning depth , There are shallow clone and deep clone .

Three , Advantages and disadvantages

1, advantage

(1) Reduce memory consumption , Less system resources , All instances share the same method , Multiple will not be created .

(2) When a prototype object inherits , Subclasses are convenient when overriding parent class prototype methods , You can call a parent class method , Further expansion .

2, shortcoming

advantage (1) It's the biggest advantage , It also brings about a serious problem , If the shared object is a reference object ( as array) It will also cause multiple instances to share the same data array, It's likely to affect each other .

Four , Usage scenarios of prototype pattern

1, When creating objects , We don't just want the object created to inherit the basic structure of its base class , You also want to inherit the data of the prototype object .
2, It is hoped that the modification of the target object will not affect the existing prototype object ( Deep cloning can be completely independent of each other ).
3, Hide details of clone operation , A lot of times , Cloning the object itself needs to involve the data details of the class itself .
4, Class initialization consumes a lot of resources , This resource includes data , Hardware resources, etc .
5, adopt new Generating an object requires very tedious data preparation or access rights , You can use the prototype pattern ;

6, One object needs to be provided for other objects to access , And each caller may need to modify its value , Consider using the prototype pattern to copy multiple objects for callers to use . In the actual project , Prototype patterns rarely appear alone , It usually comes with the factory method pattern , adopt clone To create an object , The factory method is then provided to the caller . The prototype pattern first produces a class that contains a lot of common information , Then you can make a copy , Correction details , Established a complete personality object .

Five , Shallow copy and deep copy

Shallow copy copies only pointers to an object , Instead of copying the object itself , Old and new objects still share the same memory .

Deep copy creates another as like as two peas. , The new object does not share memory with the original object , Modifying a new object does not change to the original object . 

1, Shallow copy code example
package designMode.advance.prototype; public class Sheep implements Cloneable
{ private String name; private int age; private String color; private String
address = " Mongolian sheep "; public Sheep friend; // It's the object , What will cloning do public Sheep(String name,
int age, String color) { super(); = name; this.age = age; this.color
= color; } public String getName() { return name; } public void setName(String
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 , Use default clone Methods @Override
protected Object clone() { Sheep sheep = null; try { sheep =
(Sheep)super.clone(); } catch (Exception e) {
System.out.println(e.getMessage()); } return sheep; } } package
designMode.advance.prototype; public class Client { public static void
main(String[] args) { System.out.println(" Prototype pattern completes the creation of objects "); Sheep sheep = new
Sheep("tom", 1, " white "); sheep.friend = new Sheep("jack", 2, " black "); 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()); } }

2, Deep copy code example
package designMode.advance.prototype; import; 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 of the properties of this class , All of them String , So we use the default clone Just finish @Override protected Object clone()
throws CloneNotSupportedException { return super.clone(); } } package
designMode.advance.prototype; import*; public class DeepProtoType
implements Serializable, Cloneable { public String name; //String attribute public
DeepCloneableTarget deepCloneableTarget;// reference type public DeepProtoType() {
super(); } // Deep copy - Through the serialization of objects ( recommend ) public Object deepClone() { // Create a stream 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); // The current 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) { e.printStackTrace(); return null; } finally { // Close the flow try {
bos.close(); oos.close(); bis.close(); ois.close(); } catch (Exception e2) {
System.out.println(e2.getMessage()); } } } } package
designMode.advance.prototype; public class Client { public static void
main(String[] args) { // TODO Auto-generated method stub DeepProtoType p = new
DeepProtoType(); = " Song Jiang "; p.deepCloneableTarget = new
DeepCloneableTarget(" Daniel ", " Calf "); // Deep copy DeepProtoType p2 = (DeepProtoType)
p.deepClone(); System.out.println("" + + "p.deepCloneableTarget="
+ p.deepCloneableTarget.hashCode()); System.out.println("" + +
"p2.deepCloneableTarget=" + p2.deepCloneableTarget.hashCode()); } }

Six ,JDK Archetypal patterns in Web Services

The essence of prototype pattern is to copy the prototype to create new objects , Copy is better than new Faster ways to create objects , When you need to create a large number of new objects of the same class, you can consider the prototype pattern . But it should be noted that the general cloning is only shallow cloning ( Shallow cloning : It's just about the object hash It's not the same , But the object member variable in the object hash The value is the same ) Some scenarios may require deep cloning , Then we need to rewrite it clone method , with ArrayList take as an example :

©2019-2020 Toolsou All rights reserved,
JS How to operate java Realize the function of grabbing red packets C Language programming to find a student's grade The United Nations 《 Glory of Kings 》 Please go to the studio : To save the earth Dialogue between apple and Nissan suspended ,Apple Car How's it going ?CSS architecture design China's longest high speed rail officially opened ! The fastest way to finish the race 30.5 hour First knowledge MySQL Comprehensive review ( dried food )2021 year 1 Monthly programmer salary statistics , average 14915 element How to use it quickly html and css Write static page