“Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.”

Design Patterns: Elements of Reusable Object-Oriented Software

Instantiating a class multiple times can be resource intensive, and can result in repeating the very same code multiple times. Sometimes it is more convenient to copy or clone your existing objects. Fortunately, the .NET Framework has built-in support for these cases, the aforementioned IClonable interface. This interface contains only one method, the Clone, which returns Object. So any time you need to use the Prototype pattern, just implement IClonable, and you are good to go.

A little about the idea: imagine that you are working with a complex class, such as one representing a table of data from a SQL database. You’d do something with it, then you’re in the need of the same data again. Instead of rebuilding the whole object again, you should clone the first one, and call your methods on it. It saves you from writing the same code twice, and the cost of creating a new object on the heap.

To be straightforward, let’s enlist the participants here, too:

  • Prototype: the abstract class/interface defining the prototype method, IClonable.
  • ConcretePrototype: the derivate/implementer of Prototype.
  • Client: our program, which calls the Clone method to create a prototype of the ConcretePrototype.

Some code baked in the .NET Framework:

public interface IClonable
                Object Clone();
public class System.Data.DataSet
                public  virtual DataSet Clone()
public  static void Main()
                DataSet ds = new DataSet();
                //Some lengthy initializing code
                //Hoops, we need another one!
                DataSet ds2 = ds.Clone();

Further  Readings

Prototype Pattern on Wikipedia

Design Patterns (book) pp 117-126


Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: