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"

Covariance and Contravariance-General Discussion

If you have just started the exploration of .Net Framework 4.0, two terms namely Covariance and Contravariance might have been heard. The concept that these terms encapsulate are used by most developer almost daily, however there has never been any botheration about the terminologies. Now, what actually these terms mean and how are these going to affect us as a developer, if we dive in to the details. The simple answer is it’s always good to know your tools before actually using them. Enough philosophy, let’s get to the business. Starting the discussion let me reiterate that in addition to Covariance and Contravariance, there is another terminology, Invariance. I’ll by start here by diving into the details of Invariance and then proceed further. Invariance: Invariance can be better understood by considering the types in .Net.>net has basically two type, value-types and reference-types. Value types (int, double etc) are invariant i.e. the types can’t be interchanged either

Advanced WCF

In this post, I am sharing the link of articles about  advanced topics in WCF. The List of articles is exhaustive and can serve as your repository for all WCF queries. Concurrency,Throttling & Callbacks  WCF Concurrency (Single, Multiple and Re entrant) and Throttling   WCF-Interop and BinarySecurityToken  WCF Callbacks  Creating Web Services From WSDL Link1 Link2 Link3 Link4 WCF-Security WCF over HTTPS   Transport Security(basic)/HTTPS UserNamePasswordValidator ServerCertificateValidationCallback 9 simple steps to enable X.509 certificates on WCF - CodeProject http://www.codeproject.com/KB/WCF/9StepsWCF.aspx?display=Print Message Security(Certificate)/PeerTrust Securing WCF Services with Certificates. - CodeProject http://www.codeproject.com/KB/WCF/wcf_certificates.aspx Message Security(Certificate)/ChainTrust How To Configure WCF Security Using Only X.509 Certificates - CodeProject http://www.codeproject.com/KB/webservices/WCFx509S