Design Pattern-prototype Pattern)

Source: Internet
Author: User

 

Example:
Sun Wukong's monkey hair:Sun Wukong pulls out a monkey hair, and a little blow will become a lot of Sun Wukong.
Box in Red Police:Some small boxes (magic boxes) will appear when playing with red police, and some small boxes will become the same tank when hit by a tank.

It is very easy to implement the prototype mode in C #. There is a clone method in the icloneable interface. As long as this interface is implemented, the clone method can be rewritten to copy objects.
In the prototype mode, copies are classified into "shortest copy" and "Deep copy ":
"Shortest copy ":Copy the value of a member variable of the value type. For a member variable of the reference type, only the reference is copied and the referenced object is not copied.
"Deep copy ":Copy the value of a member variable of the value type, and copy the referenced object of the referenced type.

 

//Abstract prototype,The icloneable interface is implemented to provide implementation rules for the "Specific prototype" class.
Abstract class prototype: Icloneable
{
Private string S;
Public prototype (string Str)
{
This. S = STR;
}
// Display member variable information
Public void show ()
{
Console. writeline (s );
}
// The clone method in the icloneable interface is not implemented, which is left to the "Specific prototype" class for implementation.
Public abstract object clone ();
}
//PrototypeThat is, the class of the object to be copied. It inherits the sub-Abstract prototype.
Class concreteprototype: Prototype
{
Public concreteprototype (string Str)
: Base (STR)
{}
// Implements the clone method not implemented in the "abstract prototype"
Public override object clone ()
{
// Call the implementation of the memberwiseclone method in the object classShortest copy.
Return (prototype) This. memberwiseclone ();
}
}
// Customer Program
Public class client
{
Public static void main ()
{
Concreteprototype p1 = new concreteprototype ("Hello World ");
// Copy p1
Concreteprototype P2 = (concreteprototype) p1.clone ();
P1.show ();
P2.show ();
}
}

Deep copy and shallow copy:
Shortest: you only need to execute it in the clone method of the "Specific prototype" class.Return this. memberwiseclone ();In this example, we can copy objects in a shortest.
Deep copy: In the clone method of the "Specific prototype" classInstantiate a new "prototype" object and assign the value of the current object member variable to the new object member variable.
// Deep copy
Class deepcopy: icloneable
{
Private list <string> array = new list <string> ();
Public deepcopy (Params string [] Str)
{
Foreach (string s in Str)
{
Array. Add (s );
}
}
// Modify the member variable to verify whether deep copy is implemented.
Public void add (string S)
{
Array. Add (s );
}
Public object clone ()
{
// Instantiate a new deepcopy object and initialize the member variables in the constructor.
ReturnNew deepcopy (array. toarray ());
}
// Display the member variable content of the current object
Public void show ()
{
Console. writeline ("===== deepcopy ===== ");
Foreach (string s in array)
{
Console. writeline (s );
}
}
}
Class Client
{
Public static void main (string [] ARGs)
{
Deepcopy Dc = new deepcopy ("hello", "world ");
// Call the clone method of DC to copy the object. The copy object is a deep copy.
Deepcopy dd = (deepcopy) DC. Clone ();
DC. Add ("Hello C #");
DC. Show ();
Dd. Show ();
}
}

A complete example:
This example demonstrates the implementation of the prototype mode in the "magic box" in the Red Police. The two lines mentioned in this example are light copies of the Code.
// Abstract prototype class, which is the parent class of all vehicles and implements the icloneable interface.
Abstract class vehicle: icloneable
{
Protected hashtable Info; // stores Vehicle Information (RGB color value and Life)
Public Vehicle (INT red, int green, int blue, int blood)
{
Info = new hashtable ();
Info. Add ("red", red );
Info. Add ("green", green );
Info. Add ("blue", blue );
Info. Add ("blood", blood );
}
// Display the information in the vehicle member variable
Public Virtual void show ()
{
Console. writeline ("====== the vehicle property ===== ");
Foreach (dictionaryentry de in info)
{
Console. writeline (De. Key + ":" + De. value );
}
}
// The method to reduce the lifetime of a vehicle when it is attacked.
Public void attacked (INT bloodloose)
{
Info ["blood"] = (INT) info ["blood"]-bloodloose;
}
// Method to be implemented by the abstract prototype
Public abstract object clone ();
}
// "Specific prototype" long angle Tank
Class horntank: Vehicle
{
// Tank type name
Private const string type = "horn tank ";
Public horntank (INT red, int green, int blue, int blood)
: Base (red, green, blue, blood)
{}
Public override void show ()
{
Base. Show ();
Console. writeline (type );
}
Public override object clone ()
{
// Implements deep copy of the long-angle Tank
Return new horntank (INT) info ["red"], (INT) info ["green"], (INT) info ["blue"], (INT) info ["blood"]);
// A shortest copy of the long-angle Tank
// Return this. memberwiseclone ();
}
}
// "Specific prototype" light tank
Class lighttank: Vehicle
{
// Tank type name
Private const string type = "light tank ";
Public lighttank (INT red, int green, int blue, int blood)
: Base (red, green, blue, blood)
{}
Public override void show ()
{
Base. Show ();
Console. writeline (type );
}
Public override object clone ()
{
// Realize deep copy of light tanks
Return new lighttank (INT) info ["red"], (INT) info ["green"], (INT) info ["blue"], (INT) info ["blood"]);
// Implements shallow copy of light tanks
// Return this. memberwiseclone ();
}
}
// Magic Box subclass, which can generate the same new tank
Class magicbox
{
Public Vehicle open (Vehicle v)
{
// Generate a new object based on V.
Return (vehicle) v. Clone ();
}
}
Class Client
{
Public static void main (string [] ARGs)
{
// A light tank
Lighttank lT = new Lig httank (100,200,150,100 );
// The tank has been destroyed by a lifecycle of 46 points, and the remaining lifecycle is 54 points.
Lt. Attacked (46 );
// A magic box
Magicbox MB = new magicbox ();
// When the magic box is opened, the same light tank is copied in depth, and the new light tank has only 54 points of life.
Vehicle VE = Mb. Open (LT );
// The copied light tank has a life value of. The life value of the original light tank is not affected due to the deep copy.
Ve. Attacked (23 );
Lt. Show ();
Ve. Show ();
}
}
Running result:

Prototype Manager

Prototype manager is used to manage the objects to be created. Implements unified management of multiple "Specific Prototypes.

Someone asked why it is so troublesome to copy a class directly using the new operator?
In fact, you can directly use the new operator and prototype to create an object. In prototype mode, the status of the current object is dynamically extracted, and a new object instance is generated using the status of the current object. (CHE Yanlu)

Objects should be created in the prototype mode in the following situations:
1. The object constructor is very complex. When a new object is generated, it consumes time and resources. You can use the prototype mode to create a new object.
2. During the running of the program, as some data changes along the way, it is difficult to use the constructor afterwards to construct an object that is the same as the original one.
3. I do not know the status of the current object, that is, I do not know what the value of the member variable of the current object has become. Therefore, I cannot use constructors to construct the same object as the current object.

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.