C # Design Pattern Series Tutorials-prototype mode _c# tutorial

Source: Internet
Author: User
Tags assert datetime shallow copy

1. Overview

Create a new instance by copying an existing instance. The copied instance is called a prototype, which is customizable.

2. Role in the pattern

2.1 Abstract Prototype Class (abstract Prototype): Provides a clone interface

2.2 Specific prototype class (concrete Prototype): and the specific prototype class that implements the Clone interface

3. Example: Many resumes are now supported on the job site, and it is frustrating to have to fill in every resume you create. In fact, for our job position, different resumes may be as long as the local content can be modified, instead of all rebuilding a new resume. Copy a resume, and then make local changes is the most people worry!

3.1 Implementation class diagram

  Interpretation of class diagrams

In. NET, the System namespace has provided us with a icloneable interface that contains a method clone (), which implements the prototype pattern.

3.2 Before you write the implementation code, you should understand deep copy and shallow copy.

3.2.1 Shallow copy: Copy all fields from the original object to a new object, and if the field is a value type, simply copy a copy to the new object, changing the value Type field of the new object does not affect the original object, or if the field is a reference type, copy the reference. Changing the value of a reference type field in the target object will affect the original object. For example, if an object has a field that points to a reference type (such as the work experience in an example), and we make a shallow copy of the object, then two objects will reference the same reference (that is, the same work experience).

3.2.2 Deep copy: Unlike shallow copying is the processing of reference types, deep copying points the Reference type field in the new object to the new copied object, altering any objects referenced in the new object, and does not affect the contents of the corresponding field in the original object. For example, if an object has a field that points to a reference type, such as a work experience in an example, and makes a deep copy of the object. I'm going to create a new object (ie new work experience).

3.3 Brief copy realization of resume

 <summary>///implements ICloneable interface Resume class///</summary> public class Resume:icloneable {public Resume ()
 {mworkexperience = new workexperience ();
 private string Mname;
 private string Msex;
 private int mAge;

 Private Workexperience mworkexperience;
  public string Name {get {mname;}
 set {mname = value;}
  public string Sex {get {return msex;}
 set {msex = value;}
  public int Age {get {mAge;}
 set {MAge = value;} ///<summary>///associated with a reference type///</summary> public workexperience workexperience {got {return mwo Rkexperience; } public void Setworkexperience (DateTime startdate, DateTime enddate, String company, string position) {This.mwo
  Rkexperience.company = Company;
  This.mWorkExperience.EndDate = EndDate;
  This.mWorkExperience.StartDate = StartDate;
 This.mWorkExperience.Position = Position; ///<summary>///Implementing the Clone method for the ICloneable interface///</summary>///<reTurns></returns> public Object Clone () {//. Net provides a method for the shallow copy object we provide.
 MemberwiseClone (); ///<summary>///Work experience Class///</summary> public class Workexperience {public DateTime StartDate {g Et Set
 Public DateTime EndDate {get; set;}
 public string Company {get; set;}
 public string Position {get; set;}

 }

Here is the test code

 [TestMethod]
 public void Testshallowcopy ()
 {
  Resume myfirstresume = new Resume
  {age
  =,
  Name = "Kevin Wang", 
   sex = "Male",
  };
  Myfirstresume.setworkexperience (New DateTime (2006, 7, 1), New DateTime (2007, 7, 1), "My The Company", "Software Engineer ");

  Resume Mysecondresume = (Resume) myfirstresume.clone ();
  Mysecondresume.setworkexperience (New DateTime (2007, 8, 1), New DateTime (2008, 8, 1), "My Second Company", "Software Engine Er ");

  Resume Mythirdresume = (Resume) myfirstresume.clone ();
  Mythirdresume.setworkexperience (New DateTime (2008, 8, 1), New DateTime (2009, 8, 1), "My third Company", "Senior Software E Ngineer ");

  Assert.AreEqual ("My A Company", MyFirstResume.WorkExperience.Company);
  Assert.AreEqual ("My Second Company", MySecondResume.WorkExperience.Company);
  Assert.AreEqual ("My third Company", MyThirdResume.WorkExperience.Company); 
 }

The expectation here is that three assertions are successful, but they fail because we are using a shallow copy, so Myfirstresume, Mysecondresume and Mythirdresume refer to the same object, so the end result is The workexperience.company of three resumes are "my third company".

3.4 Resume Deep Copy realization

 <summary>///implements ICloneable interface Resume class///</summary> public class Resume:icloneable {public Resume ()
 {mworkexperience = new workexperience (); ///<summary>///Here a private constructor is used to replicate the reference type to which it is connected///</summary>///<param name= "Workexperience" &GT;&L T;/param> Private Resume (workexperience workexperience) {this.mworkexperience = (workexperience) workexperience.cl
 One ();
 private string Mname;
 private string Msex;
 private int mAge;

 Private Workexperience mworkexperience;
  public string Name {get {mname;}
 set {mname = value;}
  public string Sex {get {return msex;}
 set {msex = value;}
  public int Age {get {mAge;}
 set {MAge = value;}
 Public Workexperience Workexperience {get {return mworkexperience;}  ///<summary>///Settings Experience///</summary>///<param name= "StartDate" ></param>///<param Name= "EndDate" ></param>///<param name=' Company ' ></param>///<param name= ' position ' ></param> public void setworkexperience (DateTime
  StartDate, DateTime EndDate, string company, string position) {This.mWorkExperience.Company = Company;
  This.mWorkExperience.EndDate = EndDate;
  This.mWorkExperience.StartDate = StartDate;
 This.mWorkExperience.Position = Position; ///<summary>///Implementing the Clone method for the ICloneable interface///</summary>///<returns></returns> Public obj The ECT clone () {//is no longer replicated using the MemberwiseClone method, but a new resume has been created.
  It is completely implemented internally, without concern for its implementation Resume Newresume = new Resume (this.mworkexperience);
  Newresume.msex = This.msex;
  Newresume.mname = This.mname;

  Newresume.mage = This.mage;
 return newresume;
 } public class Workexperience:icloneable {public DateTime startdate {get; set;}
 Public DateTime EndDate {get; set;}
 public string Company {get; set;}

 public string Position {get; set;} public Object Clone () {//use. Net to provide us with the shallow copy object method, because there is noReference object (string is a reference type, but. NET does a special deal for us, and it can be used like a value type). return this.
 MemberwiseClone ();

 }
 }

The test code is as follows

 [TestMethod]
 public void Testdeepcopy ()
 {
  Resume myfirstresume = new Resume
  {age
  = yes,
  Name = "Kevin Wang",
  S ex = "Male",
  };
  Myfirstresume.setworkexperience (New DateTime (2006, 7, 1), New DateTime (2007, 7, 1), "My The Company", "Software Engineer ");

  Resume Mysecondresume = (Resume) myfirstresume.clone ();
  Mysecondresume.setworkexperience (New DateTime (2007, 8, 1), New DateTime (2008, 8, 1), "My Second Company", "Software Engine Er ");

  Resume Mythirdresume = (Resume) myfirstresume.clone ();
  Mythirdresume.setworkexperience (New DateTime (2008, 8, 1), New DateTime (2009, 8, 1), "My third Company", "Senior Software E Ngineer ");

  Assert.AreEqual ("My A Company", MyFirstResume.WorkExperience.Company);
  Assert.AreEqual ("My Second Company", MySecondResume.WorkExperience.Company);
  Assert.AreEqual ("My third Company", MyThirdResume.WorkExperience.Company); 
 }

Run the test, the test passes, which is exactly what we expect.

4. Model Summary

4.1 Advantages

4.1.1 hides the creation details of objects, and improves performance for some classes that require a lot of resources to initialize.

4.1.2 when new objects are needed, you can use clone to quickly create a build without using new.

4.2 Disadvantages

4.2.1 Each class requires a clone method and must be considered in its overall view. For deep copies, each associated type is not allowed to implement the IClonable interface, and the Clone method needs to be updated for each additional or modified field.

4.3 Applicable scenarios

4.3.1 class initialization needs to digest a lot of resources, including data, hardware resources, etc.

4.3.2 to create an object that requires very cumbersome data preparation or access through new, you can use the prototype pattern

4.3.31 objects need to be accessible to other objects, and each caller may need to modify their values, consider using a prototype pattern to copy multiple objects for use by the caller.

The above is the entire content of this article, I hope to give you a reference, but also hope that we support the cloud habitat community.

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.