Preface
Prototype: Use a prototype instance to specify the object type and copy the prototype to create a new object.
Structure chart
Prototype, prototype class, declares an interface for cloning itself
Concreteprototype1 and concreteprototype2 are specific prototype classes to implement a clone operation.
Client, call, let a prototype clone itself to create a new object
In fact, the prototype mode is to create another custom object from an object without knowing any details of the Creation.
CodeImplementation
Prototype prototype design code
Public Abstract ClassPrototype {Public StringId {Get;Set;}PublicPrototype (StringID ){This. ID =ID;} // The Key to the abstract class is to have such a clone method.Public AbstractPrototype clone ();}
Concreteprototype
Public ClassConcreteprototype1: Prototype {PublicConcreteprototype1 (StringID ):Base(ID ){}Public OverridePrototype clone (){Return(Prototype)This. Memberwiseclone ();}}
This. memberwiseclone () of the clone method in its implementation class creates a superficial copy of the current object.
You can create a new object and copy the non-static fields of the current object to the new object. If the field is of the value type, perform a one-on-one copy of the field. If the field is of the reference type, copy the referenced object but do not copy the referenced object. Therefore, the original object and its copy reference the same object.
Client call
ClassProgram {Static VoidMain (String[] ARGs) {concreteprototype1 C1=NewConcreteprototype1 ("A"); Concreteprototype1 C2=(Concreteprototype1) c1.clone (); console. writeline ("Cloned: {0}", C2.id); console. Readline ();}}
Running Effect display
Summary
But. net, prototype is unnecessary for the prototype abstract class, because cloning is too common, so. NET provides the icloneable interface in the system namespace, which is the only method to clone (). In this way, you only need to implement this interface to complete the prototype mode.