C # Design Pattern: Prototype mode (PROTOTYPE) and deep copy, shallow copy

Source: Internet
Author: User
Tags shallow copy

Prototype mode (PROTOTYPE)

Defined:

Prototype mode: Specifies the kind of object created with the prototype instance, and creates a new object by copying the prototypes. The copied instance is called a prototype, and the prototype is customizable.

Prototype pattern is also a creation pattern that focuses on the creation of a large number of identical or similar objects. The prototype pattern is to create a prototype and then copy the prototype to produce a new object that is identical or similar to the prototype, or to use the prototype instance to specify the kind of object to create, and to create a new object by copying the prototypes.

Roles in the pattern

Abstract Prototype: Provides a clone interface

Concrete prototype Class (concrete Prototype): Implements the specific prototype class of the Clone interface

The advantages of the prototype model are:

      1. Prototype mode hides the complexity of creating new instances and the specific product classes to the customer, reducing the number of names the customer knows.
      2. Prototype mode allows a specific product class to be incorporated into the system by registering a prototype instance, and the customer can create and delete prototypes at runtime.
      3. The construction of subclasses is reduced. The prototype pattern is clone a prototype instead of requesting a factory method to create one, so it does not require a creator class hierarchy parallel to the specific product class.
      4. The product class does not need to determine the hierarchy of the product in advance, because the prototype pattern applies to any hierarchy.
      5. Prototype mode has the ability to dynamically load new functionality into an application. Due to the high independence of the prototype, it is easy to dynamically load new functions without affecting the old system.

The disadvantages of the prototype model are:

The most important disadvantage of prototype mode is that each class must be equipped with a clone method, and this clone method requires a holistic view of the functionality of the class. This is not difficult for new classes, but it is not always easy to retrofit existing classes.

The prototype pattern can be used for the following scenarios:

      1. Class initialization needs to digest a lot of resources, including data, hardware resources, etc.
      2. A prototype pattern can be used to produce an object through new that requires very tedious data preparation or access rights;
      3. When an object needs to be provided to other object access, and each caller may need to modify its value, consider using the prototype schema to copy multiple objects for use by the caller;
      4. When a system should be independent of its product creation, composition and representation;
      5. When the class to instantiate is specified at run time, for example, a class is created by a dynamic load;
      6. To avoid creating a plant class hierarchy that is parallel to the product class hierarchy;
      7. When an instance of a class can have only one of several different state combinations. Building the corresponding number of prototypes and cloning them may be more convenient than manually instantiating the class in the appropriate state each time.

Shallow copy and deep copy

shallow copy (shallow copy): copies all the 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, and changing the value Type field of the new object does not affect the original object; If the field is a reference type , the reference is copied, and changing the value of the reference type field in the target object will affect the original object .

deep copy: Unlike shallow copy, where reference types are handled, deep copy points the reference type field in the new object to the new copied object, altering any object referenced in the new object, without affecting the contents of the corresponding field in the original object .

Knowledge points for value types and reference types can be understood: value types and reference types in-depth understanding

Shallow copy and deep copy examples:

Copy Objects School and student:

[Serializable] Public classstudent:icloneable {Private stringName ="XXX"; Private intAge =0;  Public stringName {Get{returnname;} Set{name =value;} }         Public intAge {Get{returnAge ;} Set{age =value;} }        /// <summary>        ///new Object Implementation Clone/// </summary>        /// <returns></returns>         PublicStudent Newclone () {return NewStudent () {age = This. Age, Name = This. Name}; }        /// <summary>        ///implementing the ICloneable interface/// </summary>        /// <returns></returns>         Public ObjectClone () {return  This.        MemberwiseClone (); }} [Serializable] Public classschool:icloneable {Private stringM_name ="Init"; Private intM_number =-1; PrivateStudent m_student;  Public stringName {Get{returnM_name;} Set{M_name =value;} }         Public intNumber {Get{returnM_number;} Set{M_number =value;} }         PublicStudent Student {Get{returnm_student;} Set{m_student =value;} }        /// <summary>        ///The new object implements the clone, and if the property is a reference type, a layer new assignment is required until the property is a value type/// </summary>        /// <returns></returns>         PublicSchool Newclone () {return NewSchool () {m_name= This. M_name, M_number= This. Number, Student= This.        Student.newclone ()}; }        /// <summary>        ///implementing the ICloneable interface/// </summary>        /// <returns></returns>         Public ObjectClone () {return  This.        MemberwiseClone (); }    }

Serialized copies and reflected copies:

      Public Static classHelpertools {/// <summary>        ///serializing a deep copy/// </summary>        /// <typeparam name= "T" ></typeparam>        /// <param name= "source" ></param>        /// <returns></returns>         Public StaticT serializableclone<t>(T source) {if(!typeof(T). isserializable) {Throw NewArgumentException ("The type must be serializable.", source. GetType ().            ToString ()); }            if(Object.referenceequals (Source,NULL))            {                return default(T); } IFormatter Formatter=NewBinaryFormatter (); using(MemoryStream ms =NewMemoryStream ()) {Formatter.                Serialize (MS, source); Ms. Seek (0, Seekorigin.begin); return(T) formatter.            Deserialize (MS); }        }        /// <summary>        ///reflection attribute Shallow copy/// </summary>        /// <param name= "T" ></param>        /// <returns></returns>         Public StaticT propertyclone<t>(T t) {if(Object.referenceequals (T,NULL))            {                return default(T); } Type Type=T.gettype (); Propertyinfo[] Propertyinfos=type.            GetProperties (); Object obj= activator.createinstance<t>(); Object P= Type. InvokeMember ("", Bindingflags.createinstance,NULLTNULL); foreach(PropertyInfo PropertyInfoinchPropertyinfos) {                if(propertyinfo.canwrite) {ObjectValue = Propertyinfo.getvalue (t,NULL); Propertyinfo.setvalue (obj, value,NULL); }            }            return(T) obj; }    }
     public class Program {static void Main (string[] args) {School School = new School ()                     {Name = "Tak Yuen Primary School", Number = 0, Student = new Student () {            Name = "Rabbit Keith", age = 18};            Console.WriteLine ("************************ Original value *****************************");            Showschoolinfo (school);            Console.WriteLine ("************************ serialized deep copy *****************************");            School Serschool = Helpertools.serializableclone (School);            Serschool.name = "serialization";            Serschool.number = 1;            SerSchool.Student.Name = "Xuliehua";            SerSchool.Student.Age = 20;            Showschoolinfo (Serschool);            Showschoolinfo (school);            Console.WriteLine ("************************ new object deep copy ****************************"); School Newschool = (School) School. Newclone ();            Newschool.name = "New Object";            Newschool.number = 2;            NewSchool.Student.Name = "NewObject";            NewSchool.Student.Age = 22;            Showschoolinfo (Newschool);            Showschoolinfo (school);            Console.WriteLine ("************************ attribute reflects shallow copy *****************************");            School Proschool = Helpertools.propertyclone (School);            Proschool.name = "Reflection";            Proschool.number = 3;            ProSchool.Student.Name = "Fanshe";            ProSchool.Student.Age = 21;            Showschoolinfo (Proschool);            Showschoolinfo (school);            Console.WriteLine ("************************ clone interface Shallow copy *****************************"); School Cloneschool = (School) School.            Clone ();            Cloneschool.name = "Clone";            Cloneschool.number = 4;            CloneSchool.Student.Name = "Kelong";            CloneSchool.Student.Age = 23;            Showschoolinfo (Cloneschool); Showschoolinfo (school);        Console.ReadLine (); public static void Showschoolinfo (School School) {Console.WriteLine ("School name: {0}, School number: {1}, student name: { 2}, Student Age: {3} ", School. Name, school. Number, school. Student.name, school.        Student.age); }    }

Note: The implementing cloning method must inherit the ICloneable interface, and the serialized class must indicate the attribute [Serializable]

Summarize:

Prototype design mode Finally, from the prototype design mode, deep copy, shallow copy, reference type, value type, copy mode, and then back to the original design mode, this trip a lot.

C # Design Pattern: Prototype mode (PROTOTYPE) and deep copy, shallow copy

Related Article

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.