Prototype Design Pattern in C#

Prototype Design Pattern in C# with Examples

In this article, I am going to discuss the Prototype Design Pattern in C# with Examples. Please read our previous article where we discussed the Fluent Interface Design Pattern in C# with Examples. The Prototype Design Pattern falls under the category of the Creational Design Pattern. 

What is the Prototype Design Pattern?

As per the GoF Definition, “Prototype Design Pattern specifies the kind of objects to create using a prototypical instance, and create new objects by copying this prototype“.

To simplify the above definition, we can say that, the Prototype Design Pattern gives us a way to create new or cloned objects from the existing object of a class. That means it clones the existing object with its data into a new object. If we do any changes to the cloned object (i.e. new object) then it does not affect the original object.

Note: The Prototype Design Pattern is unique among the other Creational Design Patterns as it doesn’t require a class instead it requires an object.

Example to Understand Prototype Design Pattern in C#:

Let us understand the Prototype Design Pattern in C# with an example. In C#, when we try to copy one object to another object using the assignment (=) operator, then both objects will share the same memory address. And the reason is the assignment operator (=) copies the reference, not the object except when there is a value type field. This operator will always copy the reference, not the actual object when working with the Reference type. Please have a look at the following image for a better understanding.

Copy one object to another object using the assignment (=) operator

As you can see in the above image, we have one class called Employee having two properties i.e. Name and Department. Within the Main method, first, we create an instance of the Employee class (i.e. emp1) and set values for Name and Department properties. Then we create another employee instance (i.e. emp2) by assigning the existing employee object (i.e. emp1). And, when we change the Name property value of the emp2 object, then it also changes the name of the emp1 object and this is because both emp1 and emp2 share the same memory. So, the point that you need to remember is when we use the assignment (=) operator, it is Call By Reference only. The Complete Examples Code is given below.

using System;
namespace PrototypeDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating an Instance of Employee Class
            Employee emp1 = new Employee();
            emp1.Name = "Anurag";
            emp1.Department = "IT";

            // Creating another Instance of Employee with Existing Employee Instance using Assignment Operator
            // Both emp1 and emp2 share the same memory location as = Operator uses Call By Reference Mechanism
            Employee emp2 = emp1;

            // Changing the Name Property Value of emp2 instance, 
            // it will also change the Name Property Value of emp1 instance
            emp2.Name = "Pranaya";

            Console.WriteLine("Emplpyee 1: ");
            Console.WriteLine("Name: " + emp1.Name + ", Department: " + emp1.Department);
            Console.WriteLine("Emplpyee 2: ");
            Console.WriteLine("Name: " + emp2.Name + ", Department: " + emp2.Department);

            Console.Read();
        }
    }

    public class Employee
    {
        public string Name { get; set; }
        public string Department { get; set; }
    }
}
Output:

What is the Prototype Design Pattern?

What is Object Cloning in C#?

When we talk about Object Cloning in C#, it means it is all about the Call By Value. So, if we do any changes to one object then it will not affect the other object. Let us see how to clone the object to another object. To do so, C# provides one method called MemberwiseClone which will create a new complete copy of the object having a different memory. For a better understanding, please have a look at the below image.

What is Object Cloning in C#?

As shown in the above image, within the Employee class, we created one method i.e. GetClone and as part of that method, we are returning a clone object using the MemberwiseClone method. Then from the client code, first we are creating a new instance of the Employee class and assign the properties with some values. Next, we are creating the second object by calling the GetClone method which in turn returns a new complete copy of the emp1 object. Now, both the objects (i.e. emp1 and emp2) are independent and if we do any changes to any object, then it will not affect other objects.

Example to Understand Object Cloning in C#

The following code example shows how to create Duplicate Object or Cloned Object from an Existing object using Object Cloning. The following example code is self-explained, so please go through the comment lines for a better understanding.

using System;
namespace PrototypeDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating an Instance of Employee Class
            Employee emp1 = new Employee();
            emp1.Name = "Anurag";
            emp1.Department = "IT";

            // Instead of using Assignment Operator, now use the Clone method to create a Cloned Object
            // Both emp1 and emp2 having different Memory Address
            Employee emp2 = emp1.GetClone();

            // Changing the Name Property Value of emp2 instance, 
            // will not change the Name Property Value of emp1 instance
            emp2.Name = "Pranaya";

            Console.WriteLine("Emplpyee 1: ");
            Console.WriteLine("Name: " + emp1.Name + ", Department: " + emp1.Department);
            Console.WriteLine("Emplpyee 2: ");
            Console.WriteLine("Name: " + emp2.Name + ", Department: " + emp2.Department);

            Console.Read();
        }
    }

    public class Employee
    {
        public string Name { get; set; }
        public string Department { get; set; }

        public Employee GetClone()
        {
            // MemberwiseClone Method Creates a shallow copy of the current System.Object
            // So typecast the Object Appropriate Type
            // In this case, typecast to Employee type
            return (Employee)this.MemberwiseClone();
        }
    }
}
Output:

Example to Understand Object Cloning in C#

Points to Remember about MemberwiseClone Method in C#:
  1. The MemberwiseClone method is part of the System.Object class and creates a shallow copy of the given object. 
  2. MemberwiseClone Method only copies the non-static fields of the object to the new object
  3. In the process of copying, if a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, the reference is copied but the referenced object is not.

So, once we have understood Object Cloning, let us proceed further and understand how to implement Prototype Design Patterns in C# using Object Cloning.

Real-Time Example to Understand Prototype Design Patterns in C#:

As we discussed the Prototype Design Pattern in C# is used when we want to create a Duplicate Object or Cloned Object from an Existing object to enhance the performance of the Application. That means we need to use this Prototype Design Pattern when the creation of an object is costly as well as complex. For Example, if want to create an object after a costly database operation. Then in that case, we can cache the object, returns its clone on the next request, and update the database as and when needed which will reduce the database interaction with our application as a result the performance will be improved.

Let us proceed and implement Prototype Design Pattern in C# step by step. Once we implement the Prototype Design Pattern, then we will see the UML Diagram and we will compare the Example with the Prototype Design Pattern UML (or Class) Diagram. So, first, create a class file with the name Employee.cs and then copy and paste the following code into it. The following class is the Prototype Abstract Class and this class is used for the types of objects that can be cloned itself.

namespace PrototypeDesignPattern
{
    //The Prototype Abstract Class
    //This is an abstract class which is used for the types of object that can be cloned itself.
    public abstract class Employee
    {
        public string Name { get; set; }
        public string Department { get; set; }
        public string Type { get; set; }

        public abstract Employee GetClone();
        public abstract void ShowDetails();
    }
}

As you can see, the above class is having few properties which are common for the next-level subclasses, and two abstract methods which are going to be implemented by the child classes. 

So, next, create a class file with the name PermanentEmployee.cs and then copy and paste the following code into it. Here, you can see, the class implements the Employee abstract class and provide implementations for the two abstract methods. In the GetClone method, we have written the logic to create a shallow copy of the current object. In our next article, we will discuss Shall Copy and Deep Copy in detail. The following code is self-explained, so please go through the comment lines for a better understanding.

using System;
namespace PrototypeDesignPattern
{
    //This is a class that implements the Prototype interface for cloning itself.
    public class PermanentEmployee : Employee
    {
        public int Salary { get; set; }
        public override Employee GetClone()
        {
            // MemberwiseClone Method Creates a shallow copy of the current System.Object
            // So typecast the Object Appropriate Type
            // In this case, typecast to PermanentEmployee type
            return (PermanentEmployee)this.MemberwiseClone();
        }

        public override void ShowDetails()
        {
            Console.WriteLine("Permanent Employee");
            Console.WriteLine($" Name:{this.Name}, Department: {this.Department}, Type:{this.Type}, Salary: {this.Salary}\n");
        }
    }
}

Next, create a class file with the name TemporaryEmployee.cs and then copy and paste the following code into it. Here, you can see, the class implements the Employee abstract class and provide implementations for the two abstract methods. In the GetClone method, we have written the logic to create a shallow copy of the current object. The following code is self-explained, so please go through the comment lines for a better understanding.

using System;
namespace PrototypeDesignPattern
{
    //This is a class that implements the Prototype interface for cloning itself.
    public class TemporaryEmployee : Employee
    {
        public int FixedAmount { get; set; }
        public override Employee GetClone()
        {
            // MemberwiseClone Method Creates a shallow copy of the current System.Object
            // So typecast the Object Appropriate Type
            // In this case, typecast to TemporaryEmployee type
            return (TemporaryEmployee)this.MemberwiseClone();
        }

        public override void ShowDetails()
        {
            Console.WriteLine("Temporary Employee");
            Console.WriteLine($" Name:{this.Name}, Department: {this.Department}, Type:{this.Type}, FixedAmount: {this.FixedAmount}\n");
        }
    }
}

Now, within the Client code, we need to test whether the Clone Method working as expected or not. In our example, the Main method of the Program class is nothing but the client. So, please modify the Main method of the Program class as follows. The following example code is self-explained, so please go through the comment lines for a better understanding.

using System;
namespace PrototypeDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating an Instance of Permanent Employee Class
            Employee emp1 = new PermanentEmployee()
            {
                Name = "Anurag",
                Department = "IT",
                Type = "Permanent",
                Salary = 100000
            };

            //Creating a Clone of the above Permanent Employee
            Employee emp2 = emp1.GetClone();

            // Changing the Name and Department Property Value of emp2 instance, 
            // will not change the Name and Department Property Value of the emp1 instance
            emp2.Name = "Pranaya";
            emp2.Department = "HR";
            emp1.ShowDetails();
            emp2.ShowDetails();

            // Creating an Instance of Temporary Employee Class
            Employee emp3 = new TemporaryEmployee()
            {
                Name = "Preety",
                Department = "HR",
                Type = "Temporary",
                FixedAmount = 200000
            };

            //Creating a Clone of the above Temporary Employee
            Employee emp4 = emp3.GetClone();

            // Changing the Name and Department Property Value of emp4 instance, 
            // will not change the Name and Department Property Value of the emp3 instance
            emp4.Name = "Priyanka";
            emp4.Department = "Sales";
            emp3.ShowDetails();
            emp4.ShowDetails();
            
            Console.Read();
        }
    }
}
Output:

Real-Time Example to Understand Prototype Design Patterns in C#

Prototype Design Pattern UML (Class) Diagram:

Once we understand how to implement the Prototype Design Pattern in C#, let us try to understand the UML (Unified Modeling Language) or Class diagram of the Prototype Design Pattern. For a better understanding, please have a look at the following diagram which shows the different components of the Prototype Design Pattern. Here, I am comparing the Prototype Design Pattern UML diagram with our example, so that you can easily understand the different components of the Prototype Design Pattern.

Prototype Design Pattern UML (Class) Diagram

Let us understand each component of the Prototype Design Pattern:

  1. Prototype: This is going to be an interface or abstract class that is used for the types of objects that can be cloned itself. In our example, it is going to be the Employee Abstract Class.
  2. ConcretePrototype: This is going to be the class that implements the Prototype abstract class or interface for cloning itself. In our example, it is going to be the PermanetEmployee and TemporaryEmployee Classes.
  3. Client: The client is nothing but the class that creates a new object by asking a prototype to clone itself.

While working with object cloning, we need to understand two things i.e. Shallow Copy and Deep Copy. So, in the next article, I am going to discuss the Shallow Copy and Deep Copy in C# with Examples. In this article, I try to explain the Prototype Design Pattern in C# with Examples. I hope you understood the need and use of the Prototype Design Pattern in C# with Examples.

4 thoughts on “Prototype Design Pattern in C#”

  1. blank

    If you create the 2nd object by using new keyword, then you need to reassign the respective (same) values. No need for clone. it is cloning.

Leave a Reply

Your email address will not be published. Required fields are marked *