Prototype Pattern

  • Creational Pattern
  • The intent of this pattern is to specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
  • Prototype:-  declares an interface for cloning itself.
  • Concreteprototype :- implements an operation for cloning itself.
  • Client:- creates a new object by asking a prototype to clone itself.
				
					namespace prototypepattern
{
    public interface  Person
    {
        public string Name { get; set; }
        public Person Clone();
    }

    public class Manager : Person
    {
        public  string Name { get; set; }

        public Manager(string name)
        {
            Name = name;
        }

        public Person Clone()
        {
            return (Person)MemberwiseClone();
        }
    }

    public class Employee : Person
    {
        public string Name { get; set; }
        public Manager Manager { get; set; }
        public Employee(string name, Manager manager)
        {
            Name = name;
            Manager = manager;
        }
        public Person Clone()
        {
            return (Person)MemberwiseClone();
        }
    }
}

				
			
				
					// See https://aka.ms/new-console-template for more information



using prototypepattern;

var manager = new Manager("Anurag");
var managerClone = (Manager)manager.Clone();
Console.WriteLine($"Cloned Manager::{managerClone.Name}");



var employee = new Employee("Narasimha", managerClone);
var employeeclone = (Employee)employee.Clone();
Console.WriteLine($"Employee is {employeeclone.Name} & manager is {employeeclone.Manager.Name}");

managerClone.Name = "Abhishek";
Console.WriteLine($"Employee is {employeeclone.Name} & manager is {employeeclone.Manager.Name}");


				
			

Cloned Manager::Anurag
Employee is Narasimha & manager is Anurag
Employee is Narasimha & manager is Abhishek

Leave a Comment