1. Why use a prototype? Benefits of Prototype
For example, we have a toolbar button and a new button, which is an instance of ToolbarButton. It has the length and width attributes, and all attributes are assigned values.
Now we need to add another save button, which is also an instance of ToolbarButton. It also has the length and width attributes, but it has not been assigned a value. Its value is the same as the value of the new button.
If we do not need a prototype design pattern, we may re-assign the value. If we use the prototype design mode, we can use the new button as the prototype of the Save button. In this case, you do not need to assign a value to the Save button. Its default length and width are the same as those of the new button.
2. How to use a prototype in C?
Because the instance of the class is a reference type, to use the data of the instance in the original class, you can only use the clone method.
The Clone methods are divided into deep clone and shortest clone.
The shortest clone method is provided in C #, that is, MemberwiseClone ()
C # example of shortest Clone:
Using System;
Namespace DesignPattern
{
Public class ToolbarButton: ICloneable // implement the Clone Interface
{
Private int _ Width;
Private int _ Height;
Public ToolbarButton ()
{
}
Public int Width
{
Get
{
Return _ Width;
}
Set
{
_ Width = value;
}
}
Public int Height
{
Get
{
Return _ Height;
}
Set
{
_ Height = value;
}
}
Public object Clone ()