Creational design pattern that lets you copy existing objects without making your code dependent on their classes.
When you want to make copy of any object , you have to go through all the properties of that object and assign them to new object.
This works but it's not perfect copy because some properties are private and you cannot access them outside of the class.
Prototype design pattern solves this problem by creating a copy of the object using a method called Clone().
Use case
When the cost of creating a new object is expensive or complicated.
When you want to avoid the overhead of initializing an object from scratch.
Avoid it when you have class with circular references.
Code
//Prototype of a Person classpublicabstractclassPerson{protectedPerson(stringname,intage){Name=name;Age=age;}publicstringName{get;set;}publicintAge{get;set;}publicabstractPersonClone();}//Concrete Implementation of Teacher classpublicclassTeacher:Person{publicTeacher(stringname,intage,stringsubject):base(name,age){Subject=subject;}publicstringSubject{get;set;}publicoverridePersonClone(){returnnewTeacher(Name,Age,Subject);}publicoverridestringToString(){return$"Teacher: {Name}, Age: {Age}, Subject: {Subject}";}}//Concrete Implementation of Student classpublicclassStudent:Person{publicStudent(stringname,intage,stringgrade,Teacherteacher):base(name,age){Grade=grade;Teacher=teacher;}publicstringGrade{get;set;}publicTeacherTeacher{get;set;}publicoverridePersonClone(){returnnewStudent(Name,Age,Grade,(Teacher)Teacher.Clone());}publicoverridestringToString(){return$"Student: {Name}, Age: {Age}, Grade: {Grade}, Teacher: {Teacher.Name}";}}
privatestaticvoidMain(){//Client codevarteacher=newTeacher("John Doe",35,"Mathematics");Console.WriteLine(teacher);varstudent=newStudent("Jane Smith",16,"10th Grade",teacher);Console.WriteLine(student);varclonedTeacher=(Teacher)teacher.Clone();clonedTeacher.Name="John Doe Clone";Console.WriteLine(clonedTeacher);varclonedStudent=(Student)student.Clone();clonedStudent.Name="Jane Smith Clone";Console.WriteLine(clonedStudent);//You can create list of person and create copy of them without knowing their concrete typevarpeople=newList<Person>{teacher,student};varclonedPeople=people.Select(p=>p.Clone()).ToList();}