Friday, June 14, 2013

Prototype Design pattern in C#


Today we will learn prototype design pattern in software development. Prototype design pattern is used to make copy of any object. Now question may come in your mind, what we will do by making a copy of one object ? let me explain one scenario where prototype pattern comes in play.
You want to send invitation request to all of your friend in your birthday and I am assuming that all of your friend stay near to your house not much far. And as all are near to your house there address will be very similar or slightly different to each other. Now I am assuming in address you will mention
Country, State, City,PIN etc etc.

And those will be same for all of your friend. Now if you make one primary copy and copy all other from primary one then your task will reduce by 70%. Yes, I know you will tell me what about friend name. Yes only that attribute you have to set for each and every object, That’s why I said 70% otherwise I would say 100 %  J .
Here is the code for Prototype pattern implementation.

public Location Clone(Location objLoc)
 {
            return (Location)objLoc.MemberwiseClone();
        }

And it is the hero of Prototype pattern.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;

namespace BlogProject
{
    // Prototype Design patern in C#
    class Location
    {
        public string CountryName { get; set; }
        public string StateName { get; set; }
        public String DistrictName { get; set; }
        public string RepecientName { get; set; }

        public Location Clone(Location objLoc)
        {
            return (Location)objLoc.MemberwiseClone();
        }

    }


    class Program
    {
        static void Main(string[] args)
        {

            Location L1 = new Location();
            L1.CountryName = "India";
            L1.StateName = "West Bengal";
            L1.DistrictName = "Howrah";
            L1.RepecientName = "Sourav Kayal";

            Location L2 = new Location();

            L2 = L1.Clone(L1);
            L2.RepecientName = "Prasanta Kumar Kayal";

            Console.WriteLine("Country Name:- "+ L2.CountryName +"\n");
            Console.WriteLine("State Name:- " + L2.StateName + "\n");
            Console.WriteLine("District Name:- " + L2.DistrictName + "\n");
            Console.WriteLine("Recipient Name:- " + L2.RepecientName + "\n");
            Console.ReadLine();
        }
    }
}



No comments:

Post a Comment