How to Use the C # language to implement the prototype

Source: Internet
Author: User
Tags object serialization

Prototype:Use the prototype instance to specify the type of the object to be created, and copy the prototype to create a new object.

 

In Journey to the West, Sun Wukong can copy (clone) Multiple external bodies according to his own shape, as shown in 1. This technique is called prototype in the field of object-oriented software design, sun Wukong is called a prototype object.The prototype mode copies a prototype object to obtain multiple new objects identical to the prototype object.

 

Figure 1 Sun Wukong

The prototype mode structure 2 is shown below:

 

Figure 2 prototype Schema

The key to implementing the prototype mode is how to implement the clone method. Different programming languages provide different clone method implementation mechanisms. The following describes two clone implementation methods commonly used in the C # language.

 

 1. General Implementation Method

The general clone implementation method is to instantiate an object of the same type as its own in the clone method of a specific prototype class, return it, and pass relevant parameters to the newly created object, make sure that their member variables are the same. The sample code is as follows:

Abstract class prototype {public abstract prototype clone ();} class concreteprototype: Prototype {private string ATTR; // member variable Public String ATTR {get {return ATTR ;} set {ATTR = value ;}// clone method public override prototype clone () {concreteprototype prototype = new concreteprototype (); prototype. ATTR = ATTR; return prototype ;}}

In the customer class, you only need to create a concreteprototype object as the prototype object, and then call its clone () method to obtain the corresponding clone object, as shown in the following code snippet:

……ConcretePrototype prototype = new ConcretePrototype();ConcretePrototype copy = (ConcretePrototype)prototype.Clone();……

This method is a general implementation of the prototype model and has nothing to do with the features of the programming language itself. In addition to C #, other object-oriented programming languages can also use this method to clone the prototype.

In the general implementation method of the prototype mode, you can manually write the clone () method to achieve shortest cloning and deep cloning. Objects of the reference type can be copied by assigning values in the clone () method. This is a method of shortest cloning () the method creates a new member object for replication, which is a deep clone implementation scheme. C # The string (string/string) objects in the language have special characteristics. As long as the content of the two strings is the same, whether directly assigning values or creating new objects, they always have only one copy in the memory. For more information, see"C # string resident Mechanism"Related information.

2. memberwiseclone () method and icloneable interface in C #

In C #,Memberwiseclone () methodThis method is used for shortest cloning. It is easy to use. You can directly call the memberwiseclone () method of an existing object to clone it. The following code is used:

// Member class member {} class concreteprototypea {private Member member; // member object Public Member member {get {return member;} set {member = value ;}} // clone method public concreteprototypea clone () {return (concreteprototypea) This. memberwiseclone (); // light clone }}

In the customer class, you can directly call the clone () method of the prototype object to create a new object, as shown in the following code snippet:

……ConcretePrototypeA prototype, copy;prototype = new ConcretePrototypeA();copy = prototype.Clone();Console.WriteLine(prototype == copy);Console.WriteLine(prototype.Member == copy.Member);……

In the preceding client code snippet, the output statement "console. writeline (prototype = copy); "the output result is" false ", and the output statement is" console. writeline (prototype. member = copy. member); "indicates that the clone method is shortest clone.

In addition to the memberwiseclone () method,Icloneable InterfaceIt can also be used to create a copy of the current object. The Code is as follows:

public interface ICloneable{    object Clone();}

The icloneable interface acts as the abstract prototype class. A prototype is usually used as a subclass to implement this interface, as shown in the following code:

Class concreteprototypeb: icloneable // implement the icloneable interface {private Member member; Public Member member {get {return member;} set {member = value ;}} // implement deep clone public object clone () {concreteprototypeb copy = (concreteprototypeb) This. memberwiseclone (); member newmember = new member (); copy. member = newmember; return copy ;}}

The client code snippets are as follows:

……ConcretePrototypeB prototype, copy;prototype = new ConcretePrototypeB();copy = (ConcretePrototypeB) prototype.Clone();Console.WriteLine(prototype == copy);Console.WriteLine(prototype.Member == copy.Member);……

In this client-class code snippet, the output statement "console. writeline (prototype = copy); "the output result is" false ", and the output statement is" console. writeline (prototype. member = copy. member); "the output result is also" false ", indicating that the clone method here is deep clone.

When implementing the icloneable interface, we usually provide deep cloning methods except memberwiseclone. In addition to manual deep cloning by directly creating new member objects, deep cloning can also be achieved through reflection, serialization, and other methods, when serialization is used, all referenced objects must be serializable ).

The following describes how to use the serialization mechanism of c # To implement deep cloning. serialization involves two steps.

First, you must mark the concreteprototype and member as serializable, as shown below:

[Serializable]class ConcretePrototype{    private Member member;        ……}[Serializable]class Member{    ……}

Modify the clone () method of the concreteprototype as follows:

// Achieve deep clone public concreteprototype clone () {concreteprototype clone = NULL; filestream FS = new filestream ("temp. dat ", filemode. create); binaryformatter formatter = new binaryformatter (); try {formatter. serialize (FS, this); // serialization} catch (serializationexception e) {console. writeline ("failed to serialize. reason: "+ E. message); throw;} finally {FS. close ();} filestream fs1 = new filestream ("temp. dat ", filemode. open); binaryformatter formatter1 = new binaryformatter (); try {clone = (concreteprototype) formatter1.deserialize (fs1); // deserialization} catch (serializationexception e) {console. writeline ("failed to deserialize. reason: "+ E. message); throw;} finally {fs1.close ();} return clone ;}

In the clone () method of the above Code, the member object is also copied while the prototype object is successfully copied, achieving deep cloning.

In the above deep clone implementation code, Object serialization and deserialization can be implemented by using the filestream class and binaryformatter class. First, the current object is written into the stream using serialization, then, get the object from the stream using deserialization. Because the member object of an object will be written into the stream along with this object during serialization, a new object containing the member object will be obtained during deserialization, therefore, serialization and deserialization can be used to achieve deep cloning.

[Author: Liu Wei http://blog.csdn.net/lovelion]

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.