Skip to main content

Creational Design Patterns-Prototype Pattern


ProtoType Pattern

Given a key, the program creates an object of the required type, not by instantiation, but by copying a clean instance of the class.

The beauty of the patters is it uses the pre-existing objects to get the data and references.

Example:

public abstract class WorkForce
{
    public abstract WorkForce Clone();

    public string Name { get; set; }
    public string Role { get; set; }
}


public class Scriptors : WorkForce
{
    public string technology { get; set; }

    public override WorkForce Clone()
    {
        return (WorkForce)MemberwiseClone();
    }

    public override string ToString()
    {
   return string.Format("Name:{0} - Role:{1} - Technology:{2}", Name, Role, technology);
    }
}




public class OdinTeam : WorkForce
{
    public string Language { get; set; }
    public int Experience { get; set; }

    public override WorkForce Clone()
    {
        return (WorkForce)MemberwiseClone();
    }

    public override string ToString()
    {
        return string.Format("Name:{0} - Role:{1} - Language:{2}-Experience:{3} years", Name, Role, Language, Experience);
    }
}

The classes above create the basic skeleton to be used in the pattern.

Let us now call the pattern to see the real magic

protected void Page_Load(object sender, EventArgs e)
    {
        DevelopersTest();
        ScriptorsTest();
    }

    public void DevelopersTest()
    {
        Response.Write("ODIN Team Members");
        OdinTeam ot = new OdinTeam();
        ot.Name = "Pradeep";
        ot.Role = "Not Defined";
        ot.Language = "C#, Javascript";
        ot.Experience = 5;
        OdinTeam ot1 = (OdinTeam)ot.Clone();
        ot.Name = "Bhupender";
        Response.Write(ot.ToString());
        Response.Write("");
        Response.Write(ot1.ToString());
        Response.Write("");
     
   
    }

    public void ScriptorsTest()
    {
        Response.Write("Scriptors Team Members");
        Scriptors sts = new Scriptors();
        sts.Name = "Anil";
        sts.Role = "Sr. Scriptor";
        sts.technology = "Flash, Adobe";

        Scriptors sts1 = (Scriptors)sts.Clone();
        sts1.Name = "Ramesh";
        sts.Role = "Team Lead";
        Response.Write(sts.ToString());
        Response.Write("");
        Response.Write(sts1.ToString());
   
    }

Calling it in this manner displays the result as shown in the following screen shot.











If the data is simple type (does not contain references to other objects) it can be easily cloned and passed to the new object.
However if the object itself contains references to other objects, this techniques will not clone the referenced object, hence giving undesired output.

The first technique discussed here is generally what is termed as Shallow copy. In case of referenced objects a deep copy is what is required in real.

C# facilitates this “Deep Copy” thing. All that developers need to do is use serialization (using Streams).
Although any serialization technique can be used, the preferred and most efficient is using Memory Streams.

Shallow Copy:
MemberwiseClone is a method that is available on all objects. It copies the values of all fields and any references, and returns a reference to this copy.
However, it does not copy what the references in the object point to.
That is, it performs what is known as a shallow copy. Many objects are simple, without references to other objects, and therefore shallow copies are adequate.

Deep Copy:

To preserve the complete value of the object, including all its subobjects use a deep copy. Use Serialization for this.
Objects are copied to a given destination and can be brought back again at will.
The options for serialization destinations are several, including disks(Streams) and the Internet, but the easiest one for serializing objects is memory itself(Memory Stream).
Thus a deep copy consists of serializing and deserializing in one method.

 I am not implementing the deep copy part here due to lack of time, however I’ll definitely revert to it once I get some time.

Hope this article was helpful in clearing some of the concepts about the Prototype patterns.

Till next time… Happy Coding!!

Comments

Popular posts from this blog

Asp.Net 4.0: An Overview-Part-III

This is the last post in the series which will explore the following new features of ASP.Net 4.0  Performance Monitoring for Individual Applications in a Single Worker Process Web.config File Refactoring Permanently Redirecting a Page Expanding the Range of Allowable URLs Performance Monitoring for Individual Applications in a Single Worker Process It is a common practice to host multiple ASP.NET applications in a single worker process, In order to increase the number of Web sites that can be hosted on a single server. This practice results in difficulties for server administrators to identify an individual application that is experiencing problems. ASP.NET 4 introduces new resource-monitoring functionality introduced by the CLR. To enable this functionality, following XML configuration snippet is added to the aspnet.config configuration file.(This file is located in the directory where the .NET Framework is installed ) <?xml version="1.0" encoding="UTF-8...

WCF-REST Services-Part-II

HOW REST is implemented in WCF Part-I of the series explored the REST conceptually and this post will explore how REST is implemented in WCF. For REST implementation in WCF, 2 new attributes namely WebGetAttribute and WebInvokeAttribute are introduced in WCF along with a URI template mechanism that enables you to declare the URI and verb to which each method is going to respond. The infrastructure comes in the form of a binding ( WebHttpBinding ) and a behavior ( WebHttpBehavior ) that provide the correct networking stack for using REST. Also, there is some hosting infrastructure help from a custom Service¬Host ( WebServiceHost ) and a ServiceHostFactory ( WebServiceHostFactory ). How WCF Routes messages WCF routes network messages to methods on instances of the classes defined as implementations of the service. Default behavior ( Dispatching ) for WCF is to do this routing based on the concept of action. For this dispatching to work, an action needs to be present in ev...

WPF –ElementHost

In response to WPF overview-Part-I , one of my friends and a .Net enthusiast herself, requested for details on ElementHost Class of WPF (this class gave her nightmares in not getting the Children attached to it). This might be true for many other developers who are specialized in Web Applications and  have lesser exposure to windows development. As a breather to all those folks, I am here exploring this class with sincere hopes that it will provide a good insight to the class.   ElementHost as described in MSDN is “a Windows Forms control that can be used to host a Windows Presentation Foundation (WPF) element” is located under System.Windows.Forms.Integration namespace . The members of this class have details available at this location . Why is this Class used? ElementHost control is used to place a WPF UIElement on to the Windows Forms control or form. In simple words, if a developer is using the traditional Windows forms and intends to use WPF controls, this control (class) is used...