Prototype Design Pattern in C#

This is the fourth post of the Design Pattern series and in this blog post, we will discuss Prototype Design Pattern and its implementation in C# programming language. The Prototype Design Pattern is used to clone an existing object and falls into the Creational Pattern category as defined by the Gang of Four (GoF). If you are new to design patterns, I would highly recommend you to read the introductory post “Introduction to Design Patterns

What is the Prototype Design Pattern

The Prototype Design Pattern is used to create a clone or a duplicate of an existing object in order to avoid the expensive operation of new object creation. The pattern is used when object creation is an expensive affair (time-consuming, memory-intensive or complex to create)

Prototype or cloning of an object is achieved using shallow copy or deep copy of the object state in question to the cloned object. Choosing the copying mechanism can have different behavior of the cloned object. Here is the detail

  • Shallow Copy: In shallow copying, all the non-static fields and value types are copied to the new object and for the reference type, only the references are copied i.e. both the source object and the cloned object will be pointing to the same reference type and any changes made in either of them will be reflected on both the objects.
  • Deep Copy: In deep copying all and everything from the source object is copied to the cloned object, thus any changes made in either of them does not affect any of these objects.

Prototype Design Pattern When to Consider

  • The pattern fits well when the code does not depend on concrete classes of the object the need to be cloned.
  • The pattern can help to reduce the number of subclasses that differs only in the way they instantiate their objects based on some configurations.

Prototype Design Pattern UML

Prototype Design Pattern UML
Prototype design pattern – UML

The classes participating in the UML are as follows:

  • ICar: This is the interface that declares the cloning for itself.
  • ManualCar and AutomaticCar: These are the concrete implementation for cloning itself.
  • Client: This the service user and creates a new object by asking an ICar prototype to clone itself.

Advantages of the Prototype Design Pattern

  • The pattern eliminates the potential expensive overhead of initializing an object.
  • Help in optimizing the use case where multiple objects of the same type have almost similar data.
  • The pattern provides an alternative to inheritance when the object has configuration presets for complex objects.
  • Help in simplifying program structure and maintenance by allowing the cloning of every object member by using the clone method.

Disadvantages of the Prototype Design Pattern

  • Prototyping can be overkill for applications with fewer objects.
  • Implementing the pattern in an already existing class hierarchy can be difficult as they must implement the clone() method, as some object might be using internal objects that do not support copying or might have circular referencing.
  • The pattern hides the concrete classes from the client.

Prototype Design Pattern C# Implementation

Let us create a C# application to implement the pattern, here in this sample application we are going to use the shallow copy mechanism. The application uses the inbuild ICloneable interface provided by the .NET Framework.

public class Database : ICloneable
{
    #region Public Properties
    public string DatabaseName { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string ServerName { get; set; }
    #endregion

    #region Implemented Member
    public object Clone()
    {
        return this.MemberwiseClone();
    } 
    #endregion
}

Client Application

public class Client
{
    static void Main(string[] args)
    {
        Database database = new Database
        {
            DatabaseName = "EmployeeDB",
            ServerName = "CloudServer",
            UserName = "John",
            Password = "Doe"
        };

        // Database Object details
        Console.WriteLine($"Original Object# Database Name:  {database.DatabaseName}");

        // Getting the cloned object
        Database clonedDatabase = database.Clone() as Database;
        Console.WriteLine($"Cloned Object# Database Name:  {database.DatabaseName}");

        // Changing cloned object database name
        clonedDatabase.DatabaseName = "SomeOtherDB";

        Console.WriteLine($"Original Object# DatabaseName - {database.DatabaseName}");
        Console.WriteLine($"Cloned Object# DatabaseName - {clonedDatabase.DatabaseName}"); 
      }
}

Output:

Original Object# Database Name:  EmployeeDB
Cloned Object# Database Name:  EmployeeDB
Original Object# DatabaseName - EmployeeDB
Cloned Object# DatabaseName - SomeOtherDB


This concludes the post about the Prototype Design Pattern and I hope you found this post helpful. Thanks for visiting, Cheers!!!

[Further Readings: Top 5 Blazor Component Libraries |  Abstract Factory Design Pattern in C# |  Factory Method Pattern in C# |  Singleton Design Pattern in C# |  Introduction to Design Patterns |  Microsoft C# Version History |  Microsoft .NET Core Versions History |  Microsoft .NET Framework Version History |  Introduction to WPF in .NET Core |  Useful Visual Studio 2019 extensions for database projects |  Machine Learning Model Generation |  Important Global Visual Studio 2019 Shortcuts |  Datasets for Machine Learning |  Top 7 Must-Have Visual Studio 2019 Extensions |  AI vs ML vs DL – The basic differences  ]  

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x