. NET prototype Mode _ Practical skills

Source: Internet
Author: User

Definition of prototype pattern:

Use the prototype instance to specify the type of object to create and create new objects by copying them.

Prototype pattern structure diagram:

One of the most distinctive patterns in the creation pattern-the prototype pattern-is to clone an existing object, which has 2 results, one being a shallow copy and the other a deep copy.

The creation pattern is typically used to create a new object, and then we use this object to do some object work, and we can quickly create an object with a prototype pattern without having to provide a dedicated new () operation to quickly complete the creation of the object, which is certainly a very effective way to Quickly create a new object.

1. Prototype mode: Shallow copy

Defines an interface that is used to represent all color object interfaces

  <summary>
  ///Color interface
  ///</summary> public
  interface icolor
  {
    icolor Clone ();
    int Red {get; set;}
    int Green {get; set;}
    int Blue {get; set;}
  }

Give the specific code to implement the red:

  public class Redcolor:icolor
  {public
    int Red {get; set;}
    public int Green {get; set;}
    public int Blue {get; set;}

    Public Icolor Clone ()
    {return
      (icolor). MemberwiseClone (); 
    } 
  

The specific test code is as follows:

    static void Main (string[] args)
    {
      Icolor color = new Redcolor ();
      Color. Red = 255;
      Console.WriteLine ("color-red" + color.) Red);
      icolor color1 = color. Clone ();
      Color1. Red = 224;
      Console.WriteLine ("color1-red" + color1). Red);//224
      Console.WriteLine ("color-red" + color.) Red); The Check
    }

It can be found that when we modify the Red attribute value of the Color1 object, there is no effect on the property of color, that is, the modification of the object copy does not affect the state of the object itself.

2. Prototype mode: deep copy

Deep replication considerations are relatively complex, as there may be instances where there is an inheritance or referential relationship, and perhaps we need to be aware of it when we replicate it. Generally speaking, deep copy can be used in a simple deep copy of the object at the time of the scheme, You can also copy objects in the form of serialization. The following is the implementation of the prototype pattern in the form of serialization:

 using System; using System.Collections.Generic; using System.Linq; using System.Text;
    namespace ConsoleApplication4 {///<summary>///color interface///</summary> public interface Icolor {

    Icolordemo Clone ();
    int Red {get; set;}
    int Green {get; set;}
    int Blue {get; set;}
  Factroy F{get;set;} ///<summary>///Factory information for producing colors///</summary> [Serializable] public class Factroy {public str
  ing name {get; set;}
} using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text; namespace ConsoleApplication4 {///<summary>///color///</summary> [Serializable] public class Redc
    olor:icolor {public int Red {get; set;}
    public int Green {get; set;}
    public int Blue {get; set;}

    Public Factroy f {get; set;}
      Public Icolor Clone () {serializablehelper s = new Serializablehelper (); String target = S.serIalizable (this); 
    return s.derializable<icolor> (target); } 
  }
}

Serialization Help class:

<summary>
  ///serialization and deserialization auxiliary class
  ///</summary> public
  class Serializablehelper
  {
    public string Serializable (object target)
    {
      using (MemoryStream stream = new MemoryStream ())
      {
        New BinaryFormatter (). Serialize (stream, target);

        Return Convert.tobase64string (stream. ToArray ());
      }

    public object Derializable (string target)
    {
      byte[] Targetarray = convert.frombase64string (target);

      using (MemoryStream stream = new MemoryStream (Targetarray))
      {return
        new BinaryFormatter (). Deserialize (stream);
      }
    }

    Public T derializable<t> (string target)
    {return
      (T) derializable (target);
    }
  }

Test:

  static void Main (string[] args)
  {
    Icolor color = new Redcolor ();
    Color. Red = 255;
    COLOR.F = new Factroy () {name= "Hubei Factory"};
    Console.WriteLine ("Color-factroy:" + color.f.name); Hubei Factory

    icolor color1 = color. Clone ();
    Color1. Red = 234;
    Color1.f.name = "Beijing factory";
    Console.WriteLine ("Color1-factroy:" + color1.f.name); Beijing Factory
    Console.WriteLine ("Color-factroy:" + color.f.name); Hubei factory
    Console.read ();
  }

The results of the program's operation are as follows:


Conclusion: A new object is formed by serializing and deserializing. In fact, if you want to use the prototype pattern for object replication in the project, you can make deep replication in the form of serialization.

The above is the entire content of this article, I hope to help you learn, 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.