Prototype:
In a A = new A (); a B = A; it is to pass the reference instead of passing the value reference.
We add the clone () method to a to pass the value. This is the prototype.
//Prototype
Abstract class prototype
{
Private string ID;
Public prototype (string ID)
{
This. ID = ID;
}
Public String ID
{
Get {return ID ;}
}
// The key to an abstract class is to use this virtual method.
Public abstract prototype clone ();
}
//Specific prototype
Class concreteprototypel: Prototype
{
Public concreteprototypel (string ID)
: Base (ID)
{}
// Implements shortest cloning, copying value types, copying references, but not referencing objects
Public override prototype clone ()
{
Return (prototype) This. memberwiseclone ();
}
}
Program:
Concreteprototypelp1 = new concreteprototypel ("I ");
Concreteprototypel C1 = (concreteprototypel) p1.clone ();
Console. writeline ("cloned: {0}", c1.id );
Deep cloning:
//Work Experience
Class workexperience
{
Private string workdate;
Public String workdate
{
Get {return workdate ;}
Set {workdate = value ;}
}
Private string company;
Public String Company
{
Get {return company ;}
Set {Company = value ;}
}
// Clone the instance by referencing this strength
Public object clone ()
{
Return (object) This. memberwiseclone ();
}
}
Resume:
Classresume
{
Private string name;
Private string sex;
Private string age;
Private workexperience work;
Public resume (string name)
{
This. Name = Name;
Work = new workexperience ();
}
// Provides a private constructor for the clone method to clone work experience data
Privateresume (workexperience work)
{
This. Work = (workexperience) work. Clone ();
}
Public void setpersonalinfo (string sex, string age)
{
This. Sex = sex;
This. Age = age;
}
Public void setworkexperience (string workdate, string Company)
{
Work. workdate = workdate;
Work. Company = company;
}
Public void display ()
{
Console. writeline ("{0} {1} {2}", name, sex, age );
Console. writeline ("work experience: {0} {1}", work. workdate, work. Company );
}
Public object clone ()
{
Resume OBJ = New resume (this. Work );
OBJ. Name = This. Name;
OBJ. Sex = This. sex;
OBJ. Age = This. Age;
Return OBJ;
}
}
Program:
Class Program
{
Static void Main (String [] ARGs)
{
Resume A = New resume ("laruence ");
A. setpersonalinfo ("male", "29 ");
A. setworkexperience ("1998-2000", "XXX company ");
Resume B = (resume) A. Clone ();
B. setworkexperience ("1998-2006", "yyy company ");
A. Display ();
B. Display ();
Console. readkey ();
}
}