Prototype design pattern.

August 18, 2006

As we all know what a prototype is and whats the use of it. Moving on to .NET, one of the famous design patterns is the Prototype pattern. This falls under the creational patterns. It helps us to reduce the number of classes in application development. The prototype pattern is used when creating an instance of a class is very time consuming or complex in some way. Then rather than creating more instances, it is possible to make copies of the original instances and modifying them as appropriate.

This is achieved in .NET by using the ICloneable interface. So every prototype class implements the ICloneable interface from which the Clone() method is overriden in our class to provide to functionality to clone the class outside. Clone can be implemented either as a deep copy or a shallow copy. In a deep copy, all objects are duplicated; whereas, in a shallow copy, only the top-level objects are duplicated and the lower levels contain references.

The resulting clone must be of the same type as or a compatible type to the original instance.

System.Object provides a protected method MemberwiseClone which can be used to implement Shallow cloning. This method is marked as protected, so you can access this method in context of a derived class or within that class itself.

.NET defines an interface called IClonable which has to be implemented by classes that need functionality beyond the scope of shallow cloning (for deep cloning). We need to provide a suitable implementation in the Clone method of the interface to do the same. There are various ways to implement deep cloning. One method is to serialize the object into a memory stream and deserialize it back into a new object. We would need to use a Binary formatter or SOAP formatter which do a deep serialization. The problem with this approach is that the class and its members have to be marked as serializable, else the formatter would through an exception.

Reflection may be another method to achieve the same.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: