Design Pattern 5-prototype Pattern
1. Interpretation 1.1 Definition
Use a prototype instance to specify the type of the object to be created, and copy the prototype to create a new object.
1.2 Analysis
The concept description is actually an interface that can copy attributes and create new objects through this interface.
2 code parsing 2.1 reference and create an object
Let's take a look at the following code. This is a simple code for creating objects.
Score score = new Score (); Person person = new Person (score); Person person2 = (Person) person. clone (); // prototype copy Person person3 = person; print as follows: person: id = com. ahacool. designpattern. prototype. person @ 40ac8360 mName = Zhang San mMajor = ITperson2: id = com. ahacool. designpattern. prototype. person @ 52ed3bff mName = Zhang San mMajor = ITperson3: id = com. ahacool. designpattern. prototype. person @ 40ac8360 mName = Zhang San mMajor = IT
We found that person3 and person reference the same object, while person2 references the new object. As shown in:
Therefore, a new object is created when you use the prototype copy. If you use the "=" value assignment, only the reference address is passed.
2.2 implement the prototype mode
First, you need an Interface Class (ProtoType) that defines the copy interface.
Then a ConcreteProtoType is required to inherit and implement the corresponding copy interface.
Finally, you can call the interface (Client) as needed ).
Interface class (ProtoType): public interface Prototype {public Object clone ();} implementation class (ConcreteProtoType): public class Person implements Prototype {public String mName; public String mMajor; public Score mScore; public Person (Score pScore) {mName = "zhangsan"; mMajor = "IT"; mScore = pScore;} public Object clone () {Prototype = new Person (mScore); return Prototype ;}} call: Score score = new Score (); Person person = new Person (score); Person person2 = (Person) person. clone (); // prototype copy
2.3 deep copy and shortest copy
If the prototype class contains objects, such as the Person in the instance, if you want the Score to be passed not only by reference, but by creating a new object, it is a deep copy. If it is passed only by reference, it is a shallow copy. Compare the following two sections of code to understand.
Shallow copy: public Person (Score pScore) {mName = "zhangsan"; mMajor = "IT"; mScore = pScore;} deep copy: public PersonCloneObject (Score pScore) {mName = "James"; mMajor = "IT"; mScore = (Score) pScore. clone ();}
Code: https://github.com/bird7310/DesignPatternExample.git
Package name: com. ahacool. designpattern. prototype
3. Conclusion
It's not easy to write a blog. I admire those who have written many blogs and published books. It is really difficult to write things clearly and write so many articles.
At present, the idea is simple and can clarify things to achieve the goal. In the future, we will work hard on conciseness and clarity.