Johnconnor design patterns note (2) photocopiers in the procedural world-prototype patterns with shortest copies/deep copies johnconnor design patterns note (1) you must understand the UML class diagram before learning the design pattern.

Source: Internet
Author: User

-Starting from this article, we will first analyze some of the learning experiences of the five created models in the design model. At last, we will attach a directory and a schedule. I hope you can provide more support and recommendations.

In the era of no photocopiers, if you ran to the West to get the scriptures, do you think that Buddha will let you pull the scriptures home directly? Do you have a face as big as a gold record ....

The inevitable result is copying books. You copied a ten-year-old copy back to Datang. The original hand copy must be retained as a classic document, but in order to carry forward the Mahayana Dharma, You have to copy a book again, copy hundreds of thousands of books and distribute them to major temples.

In the eyes of programmers, the Buddhist scriptures are an object, and The copywriting is equivalent to a new object, and then the contents of the scriptures are filled into the new object.

Think about it. Every time we copy a book, we read the content of the book completely and cannot ignore the details to create an object. That is to say, it takes a long time to execute the constructor in the book, the efficiency is too low for every new product.

And if you accidentally copy "Huangyan Island has been an inherent territory of China since ancient times" into "the Philippines has been an inherent territory of China since ancient times" <joke>, the entire Datang will think so.

So many books need to be changed, but they cannot be changed to the Year of the Monkey and the month of the monkey. At that time, there were no Weibo posts, so you may apologize publicly. But I support this. Why should I apologize .. I have all my opinions on incorporating Japan into it.

 

I. prototype mode 

The human world invented print and more advanced photocopiers to solve the problem of re-creating <clone> another customizable object from an object without having to know any details of creation.

Our prototype is the photocopier in the program world.

Let's take a look at the implementation of prototype:

  

This diagram is a UML class diagram of the prototype model. In the design mode, class diagrams are often used to illustrate its structure. <If you have any questions about the UML class diagram, go to the first section of this series to learn about the UML class diagram: Portal>

Code of the basic prototype mode

/// <Summary> // prototype abstract class /// </Summary> public abstract class prototype {Public String text {Get; set;} public abstract prototype clone (); // The Key to the abstract class is to have such a clone method} /// <summary> /// the specific prototype class scriptures /// </Summary> public class book: prototype {public override prototype clone () {return (prototype) This. memberwiseclone (); // creates a superficial copy of the current object. }}

 

  

The memberwiseclone () method is to create a new object, and then copy the non-static fields of the current object to the new object. If the field is of the value type, perform a step-by-step copy on the field. If the field is of reference type, the referenced object is copied but not referenced. Therefore, the original object and the copy reference the same object.

This introduces the deep replication and shortest replication issues, which will be discussed later.

In this way, we do not need to copy books one by one:

Static void main (string [] ARGs) {book original = new book {text = "copy the text that you don't pay for"}; book copy1 = new book {text = original. text}; // you have already finished copying .... book copy2 = (book) original. clone (); // clone the console. writeline ("copy2.text is {0}", copy2.text );}

  

By cloning <in reality it may be a rigid print>, we can get a copy of the original without knowing the content of the book. When we need to know about it, we can learn about it again.

This is the meaning of the prototype model mentioned above. Generally, cloning is the best solution when the initialization information does not change, which hides the details of object creation, this greatly improves the performance.

For. net, the prototype mode is very well implemented, and the icloneable interface is improved in the system namespace. There is only one method to clone ().

In this way, we only need to implement this interface to complete the prototype mode. prototyoe is no longer required for the prototype abstract class:

. Net implementation prototype:

  

 

public class Book : ICloneable{    public string Text { get; set; }    public Object Clone()    {        return (Object)this.MemberwiseClone();    }}

 

  

The method of calling a method is the same as in the preceding example.

Now, we will introduce the prototype. Now let's take a look at the deep replication and shallow replication problems mentioned above.

 

Ii. Deep replication and light Replication

  Previously, we have introduced that the memberwiseclone () method creates a superficial copy. If the object field is of the reference type, only the reference is copied instead of the referenced object. Let's change the book class:

 

  

public class Book : ICloneable{    public string Text { get; set; }    public Version Version { get; set; }    public Object Clone()    {        return (Object)this.MemberwiseClone();    }    public void ShowVersion()    {        Console.WriteLine("Version {0} Author is {1}",Version.Num,Version.Author);    }}public class Version{    public int Num { get; set; }    public string Author { get; set; }}

  

In this case, the book class has the attribute version of the reference type. So what will happen during the cloning process?

Static void main (string [] ARGs) {book original = new book {text = "copy the text that you don't pay for", version = new version {num = 0, author = "" }}; book copy1 = (book) original. clone (); book copy2 = (book) original. clone (); book copy3 = (book) original. clone (); copy1.version. author = "Sun monkey"; copy2.version. author = ""; copy3.version. author = "johnconnor ";
Copy1.version. num = 1;
Copy2.version. num = 2;
Copy3.version. num = 3; copy1.showversion (); copy2.showversion (); copy3.showversion ();
Console. readkey ();}

  

The results are different from what we think. The authors of each version are monkey, gossip, and me.

  

The three versions reference the last setting. This is because, as described above, only the reference is copied, but the referenced object is not copied. During the cloning process, no object is created, now all three references point to the same version object.

This is called shortest copy. All variables of the Copied object contain the same value as the original object, but all references to other objects still point to the original object.

But this is obviously a problem. For example, we need to point the version reference in copy1, copy2, and copy3 to different objects, so that no change will occur.

This is called Deep replication. It directs the variables of the referenced object to the copied new object instead of the original referenced object.

 

Iii. Implementation of deep Replication

  Take the transcript as an example. The code structure

  

 

Public class Book: icloneable {Public String text {Get; set;} private version; public version Version {get {return version;} set {This. version = (Version) value. clone ();} // use the clone object in the Set Method of version, so that a new version object} public object clone () // implements the clone method, assign values to related fields of the new object, and return a book object {book OBJ = New Book (); obj. TEXT = This. text; obj. version = This. version; return OBJ;} public void showversion () {console. writeline ("version {0} author is {1}", version. num, version. author) ;}} public class version: icloneable {public int num {Get; set;} Public String author {Get; set;} public object clone () // implement the clone method {return (object) This. memberwiseclone ();}}

 

Then, run the console program to output the clone result:

  

 

The three results are different.

However, note that we only have one layer of reference here. If there are too many layers of deep replication or there are loop references, this is troublesome and requires extra caution.

Deep Replication involves many scenarios. For example, if the DataSet object dataset is used, it has two methods: Clone (), copy (), and clone () to copy its structure, however, data is not copied, and the prototype is replicated in a shortest manner.

The copy () method also copies data based on the replication structure, that is, the deep replication of the prototype mode.

  

Last added:

Copy1.text = "poo RuO parami"; console. writeline (original. Text );
Console. readkey ();

 

  

What do you think this sentence will output? According to the above theory, the text is of the string-reference type, and the text of all objects should reference the same string object. If you change it to one, all objects will be changed.

However, this worry is unnecessary. The input will be the first to write "text that will not pay off your life ".

 

Some people may want to jump out here. Isn't string a reference type? Why can deep replication be completed without special processing?

Because the process of assigning values to the string object itself is to create a new String object to store new values and return references to the new object. This is a feature of the C # string type.

 

<If you have any questions about string, or do not know much about the reference type and value type, I have a previous article about this issue in memory. Click the portal to enter>

 

---------------------------------------------- End --------------------------------------------------

 

Johnconnor design pattern note series directory

Johnconnor design patterns Note (I) What you must master before learning the design patterns-Understanding UML class diagrams

Johnconnor design patterns note (2) photocopiers in the procedural world-prototype mode and shortest replication/deep Replication

To be continued ......

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.