Showing posts with label prototype design pattern. Show all posts
Showing posts with label prototype design pattern. Show all posts

Tuesday 21 January 2020

prototype in C#

Prototype in C# design pattern

Step1 : Create Interface
public interface IEmployee
    {
        IEmployee Clone();
        string GetDetails();
    }

Step2: Create Class and inherit interface
    public class Developer : IEmployee
    { 
        public int Id { get; set; }
        public string Name { get; set; }      
        public string PreferredLanguage { get; set; }

       // Clone object
        public IEmployee Clone()
        {           
            return (IEmployee)MemberwiseClone();
        }
        public string GetDetails()
        {
            return string.Format("{0} - {1} - {2}", Name, Id, PreferredLanguage);
        }
    }
 
  // Create another class and inherit Interface
    public class Tester : IEmployee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string PreferredLanguage { get; set; }
        public string Address { get; set; }
        public IEmployee Clone()
        {          
            return (IEmployee)MemberwiseClone();
        }
        public string GetDetails()
        {
            return string.Format("{0} - {1} - {2} - {3}", Name, Id, PreferredLanguage, Address);
        }
    }

// Implementation place
 public class PrototypeTest
    {
        public static void Test()
        {
            Developer dev = new Developer()
            {
                Name ="Dev1",
                Id =1,
                PreferredLanguage = "en-us"
            };
            Developer devCopy = (Developer)dev.Clone();
            devCopy.Id = 2;
            devCopy.Name = "Dev2";
            Console.WriteLine(dev.GetDetails());
            Console.WriteLine(devCopy.GetDetails());
        }
    }

// Result

Dev1 - 1 - en-us
Dev2 - 2 - en-us