In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "what is the prototype pattern in Spring". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the prototype pattern in Spring"?
Brief introduction
It is defined as: > use the prototype instance to specify the type of object to be created, and create a new object by copying the instance.
Specifically, by giving a prototype object to indicate the type of object created, and then using its own implementation of the clone interface to copy the prototype object, this pattern is used to create more objects of the same type.
The advantage is that the clone () method of the > Object class is a local method that directly manipulates the binary stream in memory, so it performs better than new instantiation.
The creation process of an object instantiated through new is:
Open up a space in memory.
Create an object in the open memory space.
Call the constructor of the object to initialize the object.
The process of creating an object through clone () is:
Open up a piece of memory space according to the memory size of the original object.
Copy an existing object and clone all attribute values in the object.
Clone () has fewer calls to the constructor than new. Replicating objects using clone () performs better if there are a large number of property initializations or large objects in the constructor.
Simple example
Let's take a look at it in detail through an example:
/ * prototype abstract class Prototype * / public class Prototype implements Cloneable {/ * overrides the clone () method * / @ Override public Prototype clone () {Prototype prototype = null; try {prototype = (Prototype) super.clone ();} catch (CloneNotSupportedException e) {e.printStackTrace ();} return prototype }} / * implementation prototype class * / public class ConcretePrototype extends Prototype {public void show () {System.out.println ("prototype pattern implementation class");}} / * Test class * / public class Client {public static void main (String [] args) {ConcretePrototype cp = new ConcretePrototype (); for (int I = 0; I < 10) ConcretePrototype cloneCp +) {ConcretePrototype cloneCp = (ConcretePrototype) cp.clone (); cloneCp.show ();}
When we implement a prototype abstract class, we need to pay attention to three points:
Implement the Cloneable interface: the Cloneable interface acts like a serialization interface, except that it tells the virtual machine that the clone () method can be safely used on the class that implements the interface. In JVM, only classes that implement the Cloneable interface can be copied, otherwise a CloneNotSupportedException exception will be thrown.
Override the clone () method in the Object class: in Java, the parent of all classes is the Object class, while the Object class has a clone () method that returns a copy of the object.
Call super.clone () in the overridden clone () method: by default, the class does not have the ability to copy objects and needs to call super.clone () to do so.
Deep copy and shallow copy
When it comes to copying, we have to talk about a classic problem: deep copy and shallow copy, which is also called deep clone and shallow clone in some places.
In the prototype pattern above, after calling the super.clone () method, we first check whether the class to which the current object belongs supports clone, that is, whether the class implements the Cloneable interface.
If so, a new object of the class to which the current object belongs is created and initialized so that the value of the member variable of the new object is exactly the same as that of the member variable of the current object, but references to other objects and member properties of types such as List can only be copied. So simply calling super.clone (), which is a way to clone an object, is a shallow copy.
In order to make people more aware of the disadvantages of shallow copies, let's give a specific example:
There is a Teacher object in the Student class, and we have both classes implement the Cloneable interface:
@ Getter@Setterpublic class Student implements Cloneable {/ * * student name * / private String name; / * the teacher to which the student belongs * / private Teacher teacher; / * rewrite the cloning method and clone the student * / public Student clone () {Student student = null; try {student = (Student) super.clone () } catch (CloneNotSupportedException e) {e.printStackTrace ();} return student;}} @ Getter@Setterpublic class Teacher implements Cloneable {/ * * teacher name * / private String name; / * rewrite the cloning method, clone the teacher class * / public Teacher clone () {Teacher teacher= null Try {teacher= (Teacher) super.clone ();} catch (CloneNotSupportedException e) {e.printStackTrace ();} return teacher;}}
In the test, we first define a student and a teacher and associate them. Then copy the previous student, generate a new student, and modify the new student's teacher.
Public class Test {public static void main (String args []) {/ / define teacher 1 Teacher teacher = new Teacher (); teacher.setName ("Mr. Liu"); / / define student 1 Student stu1 = new Student (); stu1.setName ("test1"); / / teacher 1 and student 1 associate stu1.setTeacher (teacher) / / copy student 1 and generate student 2 Student stu2 = stu1.clone (); stu2.setName ("test2"); / / modify student 2's teacher stu2.getTeacher (). SetName ("Mr. Wang"); / / View the modification result System.out.println ("student" + stu1.getName () + "teacher is:" + stu1.getTeacher (). GetName ()) The teacher of System.out.println ("students" + stu1.getName () + "is:" + stu2.getTeacher (). GetName ());}}
What we want is:
The teacher of student test1 is: Mr. Liu, the teacher of student test2 is: miss Wang
But the actual result is:
The teacher of student test1 is: Mr. Wang. The teacher of student test2 is: Mr. Wang.
Observing the above running results, we can find that when we modify the teacher for student 2, the teacher of student 1 is also modified. This is the problem with shallow copies.
We can solve this problem by making a deep copy, modifying the clone () method of the Student class:
/ * rewrite the cloning method to clone both students and teachers * / public Student clone () {Student student = null; try {student = (Student) super.clone (); / / Clone teacher object Teacher teacher = this.teacher.clone (); student.setTeacher (teacher) } catch (CloneNotSupportedException e) {e.printStackTrace ();} return student;}
At this point, we run the main () method in Test again to get the desired results.
Applicable scenario
In some scenarios where objects are created repeatedly, we can use prototype patterns to improve object creation performance. For example, when creating an object in a loop, we can consider using clone () to implement it.
In addition, the prototype pattern is also widely used in open source frameworks. For example, in Spring, @ Service is singleton by default. Private global variables are used, and you need to use the prototype pattern if you don't want to affect the next injection or each context to get bean, which we can do with the following annotation, @ Scope ("prototype"). Interested friends have an in-depth understanding of the principle.
Summary
Prototype mode is a good and efficient choice for scenarios that require a large number of copies of the same object, such as users getting goods, creating objects in a loop, and so on.
At this point, I believe you have a deeper understanding of "what is the prototype pattern in Spring". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.