Geeks With Blogs
Dheeman Dutta Just Another Blog.....
The Prototype pattern helps us in creating objects from existing ones. There can be any of the two following situations that may occur .
CASE 1:
Sometimes you may need to create an object of a certain class, but you do not have all the parameters that the constructor of that object need to create that object .
CASE 2:
You need to capture the present state of an object and create another object.
In either of the two above cases , we can clone the  existing object to create the new one.
Cloning(copying) in .net can be of two types, Deep Copy and Shallow Copy.   [you can easily find the difference between the two googling in the internet. J ] .
While performing shallow copy we ususally use obj.MemberWiseClone() feature of .net. Here the cloned object has the structure and the basic properties(value types ) from which the it is cloned. But using this method, we cannot have the data that persisted deeper in the source object, i.e you might have an object that houses an ArrayList with some other object instance. Now performing shallow copy will copy the ArrayList for you in the cloned object , but will not copy the object instances in the ArrayList. You need to do a deep copy to achieve that. One of the popular methods of deep copying is by implementing System.Iclonable .
Suppose we want to clone (shallow) an existing Car object to create another Car.
                                abstract class Car
{
                public abstarct Car CloneCar();
// other methods and code
}
class MyDreamCar : Car
{
//other code
 
 
 
public override Car CloneCar()
                {
                return (MyDreamCar)this.MemberwiseClone();
 
                }
}
               
 
 
 
Posted on Saturday, June 2, 2007 5:52 PM | Back to top


Comments on this post: Design patterns - Part 3 - The Prototype Pattern

# re: Design patterns - Part 3 - The Prototype Pattern
Requesting Gravatar...
I had clone one object using memberwiseclone method and it is clone like deep.
Left by Ripal Patel on Feb 06, 2008 11:23 PM

Your comment:
 (will show your gravatar)


Copyright © Dheeman Dutta | Powered by: GeeksWithBlogs.net