Monday, September 24, 2007

* Patterns : Prototype Creational Pattern

Prototype Creational Pattern provides an interface which can be used by client to get access to already existing instance of a type which can be used as prototype by client to create new instance. Client can clone the existing object using deep or shallow copy and use it. It is used mainly when inherent cost of creating a new object is high.

Consider the following class diagram :

Above scenario goes like this :

Client needs the updated list of managers. ListAdmin can provide the list but its not latest. Now, client instead of creating the list from scratch which can be very resource consuming, picks the list from ListAdmin, creates a shallow copy of it and updates it for further use.

    public class Client
{
public static void Run()
{
ManagersList managersList = ListAdmin.getManagersList();
Console.WriteLine("Printing managersList ....");
DisplayList(managersList);
ManagersList list = (ManagersList)managersList.Clone(); // Creates a shallow copy
list.managers.Add("D_Manager1");
list.id = 2;
Console.WriteLine("Printing list ....");
DisplayList(list);
Console.WriteLine("Printing managersList again....");
DisplayList(managersList);
}

private static void DisplayList(ManagersList list)
{
Console.WriteLine("ID = " + list.id);
for(int i=0;i<list.managers.Count;i++)
{
Console.WriteLine(list.managers[i]);
}

}
}

The above client code output will be following :


Printing managersList ....
ID = 1
B_Manager1
A_Manager1
C_Manager1
Printing list ....
ID = 2
B_Manager1
A_Manager1
C_Manager1
D_Manager1
Printing managersList again....
ID = 1
B_Manager1
A_Manager1
C_Manager1
D_Manager1

Download full source code from here : Prototype Creational Pattern

No comments:

Post a Comment