[Serializable]
Public abstract class MyControlBase
{
/// <Summary>
/// Data Source
/// </Summary>
Public System. Data. DataSet MyDataSource {get; set ;}
/// <Summary>
/// Author
/// </Summary>
Public string Author {get; set ;}
Protected string Serialize ()
{
Using (System. IO. MemoryStream MS = new System. IO. MemoryStream ())
{
New BinaryFormatter (). Serialize (MS, this );
Return Convert. ToBase64String (ms. ToArray ());
}
}
Protected MyControlBase Deserialize (string objString)
{
Byte [] objArr = Convert. FromBase64String (objString );
Using (MemoryStream MS = new MemoryStream (objArr ))
{
Return new BinaryFormatter (). Deserialize (MS) as MyControlBase;
}
}
Public abstract MyControlBase Clone ();
}
/// <Summary>
/// Panel
/// </Summary>
[Serializable]
Public class MyPanel: MyControlBase
{
Public override MyControlBase Clone ()
{
String objStr = Serialize ();
Return Deserialize (objStr );
}
}
// ---------------------- Test
Public static void PrototypePattern ()
{
// The prototype mode is used to create objects, but not new,
// The clone method is used. Since it is clone, first
// There must be an initial cloned object.
// 1. Purpose of the prototype:
// 1. create complex objects and reduce initialization costs (some object constructors execute a bunch of operations ).
// 2. Simplify the creation of objects on the client (for example, to create an object, you need to upload a bunch of parameters ).
// 2. prototype application:
// 1. Controls on the toolbar of. 2. Creation of small soldiers in the game.
// 3. This example uses serialization to clone objects. This ensures full clone (including deep clone) of objects ),
// You can also perform shortest copy and deep copy manually.
MyPanel pnlTop = new MyPanel ();
PnlTop. Author = "zhaoyang ";
Button btnTop = new Button () {ToolTip = "top Button "};
PnlTop. MyDataSource = new DataSet ("ds1 ");
MyPanel pnlMain = pnlTop. Clone () as MyPanel;
PnlMain. Author = "litao ";
Console. WriteLine (pnlTop. Author );
Console. WriteLine (pnlTop. MyDataSource. DataSetName );
Console. WriteLine (pnlMain. Author );
Console. WriteLine (pnlMain. MyDataSource. DataSetName );
}