Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

ReadMe.md

Prototype Design Pattern is used to create a duplicate object or clone of the current object to enhance performance. This pattern is used when creation of an object is costly or complex

Overview

The Prototype pattern is a creational design pattern that lets you copy existing objects without making your code dependent on their classes. It's particularly useful when object creation is expensive or when you need to create objects that are similar to existing ones.

Implementation Details

This implementation demonstrates employee object cloning with both shallow and deep copy mechanisms:

Key Components:

  • Employee (Prototype): The main class that can be cloned with Name, Department, and EmpAddress properties
  • Address: A reference type property that demonstrates the difference between shallow and deep copying
  • Cloning Methods: GetShallowCopy() and GetDeepCopy() methods for different cloning strategies

Classes:

  • Employee - Prototype class with GetShallowCopy() and GetDeepCopy() methods
  • Address - Reference type class with GetClone() method for deep copying

Usage Example:

// Create original employee
Employee emp1 = new Employee
{
    Name = "Tushar",
    Department = "IT",
    EmpAddress = new Address() { address = "Jodhpur" }
};

// Shallow copy - shares reference types
Employee emp2 = emp1.GetShallowCopy();
emp2.Name = "Kuldeep";
emp2.EmpAddress.address = "Chandigarh"; // This affects emp1's address too!

// Deep copy - creates independent copies
Employee emp3 = emp2.GetDeepCopy();
emp3.EmpAddress.address = "Jaipur"; // This doesn't affect emp2's address

Cloning Types:

Shallow Copy:

  • Uses MemberwiseClone() method
  • Creates a new object but shares references to nested objects
  • Changes to reference type properties affect the original object
  • Faster and uses less memory

Deep Copy:

  • Creates completely independent copies of all objects
  • Changes to any property don't affect the original object
  • Requires manual implementation for reference types
  • Slower but provides complete isolation

Output Example:

Employee 1: Name: Tushar, Address: Chandigarh, Dept: IT
Employee 2 (Shallow Copy): Name: Kuldeep, Address: Chandigarh, Dept: IT
Employee 3 (Deep Copy): Name: Kuldeep, Address: Jaipur, Dept: IT

Benefits:

  • Reduces the cost of creating objects when creation is expensive
  • Avoids complex initialization logic by copying existing objects
  • Provides flexibility in object creation
  • Useful when you need objects that are similar to existing ones
  • Can improve performance by avoiding repeated expensive operations