IntroductionWhat is a Proto type design pattern?GOF -> A fully initialized instance to be copied or cloned. The Prototype pattern specifies the kind of objects to create using a prototypical instance.
So first create an object that allows copying himself to another object of same type, instead of creating new objects by using ‘New’ keyword. A. Prototype co-opts one instance of a class for use as a breeder of all future instances. B. Prototype is unique among the other creational patterns in that it doesn’t require a class – only an object. C. Prototypes are useful when object initialization is expensive D. Factory Method creation through inheritance. Prototype creation through delegation E. Prototype doesn’t require sub classing, but it does require an “initialize” operation. Factory Method requires sub classing, but doesn’t require Initialize. Architecture design(UML) C# Support for the Proto typeA. Shallow Copy ->Object.MemberwiseClone Method
Any object that derives from the System.Object has this method, which creates a shallow copy of the current Object. The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. 1. Value Type When a field is a value type, a bit-by-bit copy of the field is performed. 2. Reference Type When a field is a reference type, the reference is copied but the referred object is the same. So, the original object and its clone refer to the same object. For example, consider an object called SomePerson that references objects Person. A shallow copy of SomePerson creates new object SomePerson1 that also references objects Person. Look at the following example public class A
{private string _a;public A(string a){
this._a = a;
}public A Clone(){return (A)this.MemberwiseClone();
}
}
On the client Now consider another example public class SomeData{private int myVar;public int MyProperty
{get { return myVar; }set { myVar = value; }
}
}public class A{private string _a;public SomeData MySomeData;public A(string a){this._a = a;
}public A Clone(){return (A)this.MemberwiseClone();
}
}
Client side B. Deep Copy -> Object.MemberwiseClone Method As said above Deep copy is altogether different. It creates new objects. Following is the example code to implement deep copy public class SomeData
{private int myVar;public int MyProperty
{get { return myVar; }set { myVar = value; }
}
}public class A
{private string _a;public SomeData MySomeData;public A(string a)
{this._a = a;
}public A Clone()
{return (A)this.MemberwiseClone();
}public A DeepCopy()
{
A a = (A)this.MemberwiseClone();
a.MySomeData = new SomeData();
a.MySomeData.MyProperty = this.MySomeData.MyProperty;return a;
}
}
Client side code Hopes help. thank you for reading. |