Showing posts with label design Pattern. Show all posts
Showing posts with label design Pattern. Show all posts

Prototype Design Pattern in C# with Examples

 
Prototype Design Pattern in C# with Examples
Gang of Four Definition : "Prototype Design Pattern Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype"


To simplify, instead of creating object from scratch every time, you can make copies of an original instance and modify it as required.

Prototype is unique among the other creational patterns as it doesn't require a class but only an end object.
We need to choose Prototype Design Pattern when
  • Creating an object is an expensive operation and it would be more efficient to copy an object.
  • System should be independent of how its products are created, composed, and represented.
  • Objects are required that are similar to existing objects.
  • We need to hide the complexity of creating new instance from the client.
Prototype Representation






Shallow and Deep Copy : The idea of using copy is to create a new object of the same type without knowing the exact type of the object we are invoking.

Shallow Copy : copies an object's value type fields into the target object and the object's reference types are copied as references into the target object.
Deep Copy : Deep Copy copies an object's value and reference types into a complete new copy of the target objects.

Difference between Shadow and Deep Cloning


The cloning falls under two categories: shallow and deep.

  • A shallow copy copies all reference types or value types, but it does not copy the objects that the references refer to. The references in the new object point to the same objects that the references in the original object points to.

    (Only Parent Object is cloned here).
     
  • In contrast, a deep copy of an object copies the elements and everything directly or indirectly referenced by the elements.

    (Parent Object is cloned along with the containing objects)

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!!!

Fluent Interface Design Pattern in C# with Examples

Fluent Interface Design Pattern in C# with Examples

Fluent Interface Design Pattern in C# with Examples

In this article, I will talk about the Fluent Interface Design Pattern in C# with models. The Fluent Interface Design Pattern is one of the most often utilized plan designs progressively applications. The Fluent Interface Design Pattern in C# falls under the classification of Creational Design Pattern.

Note: The Fluent Interfaces and Method chaining are related to each other. Or we can say that one is a concept and the other one is its implementation. Here in this article, first, we will discuss fluent interfaces and then we will move towards method chaining.

What is the Fluent Interface Design Pattern?

The main objective of the Fluent Interface Design Pattern is that we can apply multiple properties (or methods) to an object by connecting them with dots (.) without having to re-specify the object name each time.

How to Implement Fluent Interface Design Pattern in C#?
Let us understand How to Implement the Fluent Interface Design Pattern in C# with an example. Let say, we have the following Employee class.

   public class Employee

    {

        public string FullName { get; set; }

        public DateTime DateOfBirth { get; set; }

        public string Department { get; set; }

        public string Address { get; set; }

    }


If we want to consume the above Employee class, then we generally, create an instance of the Employee and set the respective properties as shown below.

  Employee emp = new Employee()

        {

            FullName = "DotNet office",

            DateOfBirth = Convert.ToDateTime("01/01/2022"),

            Department = "Developement",

            Address = "india"

        };


The Fluent interfaces simplify your object consumption code by making your code more simple, readable, and discoverable. Is not it nice to be set the object properties as shown below?

 

Employee emp = new Employee();

            emp.NameOfTheEmployee("Dotnet office")

                    .Born("01/01/2022")

                    .WorkingOn("Developement")

                    .StaysAt("India");


f we create such kinds of interfaces, then it is like speaking a sentence that would really make the class consumption code more simple and more readable. Now the next thing is how to achieve this. To achieve this, we have something called method chaining.

What is Method Chaining?

Method chaining is a common technique where each method returns an object and all these methods can be chained together to form a single statement. In order to achieve this, first, we need to create a wrapper class around the Employee class as shown below.

 

public class FluentEmployee

    {

        private Employee employee = new Employee();

        public FluentEmployee NameOfTheEmployee(string FullName)

        {

            employee.FullName = FullName;

            return this;

        }

        public FluentEmployee Born(string DateOfBirth)

        {

            employee.DateOfBirth = Convert.ToDateTime(DateOfBirth);

            return this;

        }

        public FluentEmployee WorkingOn(string Department)

        {

            employee.Department = Department;

            return this;

        }

        public FluentEmployee StaysAt(string Address)

        {

            employee.Address = Address;

            return this;

        }

    }

 

As you can see, here we have created methods for each property. Also, notice the return of the method is set to the FluentEmployee. Now the above fluent interface is going to be consumed by the client. So, with the above FluentEmployee class in place, now the client code should looks as shown below.

        static void Main(string[] args)

        {

            FluentEmployee obj = new FluentEmployee();

            obj.NameOfTheEmployee("DotNet office")

                    .Born("01/01/2022")

                    .WorkingOn("Developement")

                    .StaysAt("India");

            Console.ReadLine();

        }


When do we need to use the Fluent Interface Design Pattern in C#?
  1. During UNIT testing when the developers are not full-fledged programmers.
  2. When you want your code to be readable by non-programmers so that they can understand if the code is satisfied with their business logic or not.
  3. If you are a component seller and you want to stand out in the market as compared to the others by making your interface simpler.

I have seen fluent interfaces are used extensively in LINQ Queries: Searching, Sorting, pagination, grouping with a blend of LINQ are some of the real-world usages of the fluent interface in combination with the builder design pattern.

Builder Design Pattern in C# with Real-time Example in C#

 

Builder Design Pattern in C# with Real-time Example in C#

In this article, I will talk about the Builder Design Pattern in C# with models. The Builder Design Pattern is one of the most often utilized plan designs progressively applications. The Builder  Design Pattern in C# falls under the classification of Creational Design Pattern.

Definition : "Separate the construction of a complex object from its representation so that the same construction process can create different representations"

Builder Design Pattern solves the situation of increasing constructor parameters and constructors of a given class by providing a step by step initialisation of Parameters. After step by step initialisation, it returns the resulting constructed Object at once.

Implementation Guidelines : We need to Choose Builder Design Pattern when

  1. We need to break up the construction of a complex object
  2. We need to create a complex object and it should be independent of the parts that make up the object
  3. The construction process must allow multiple representations of the same class

Implementation of Builder Design Pattern Real-time Example in C# 

As per the real time example for Builder design pattern is we are going build a laptop for a employee, and for doing a setup or build a laptop , we need couple of the configuration and those are Builder RAM, SSD, USB Mouse etc
So lets build a laptop

Step 1: Create a class file with the name SystemDetails.cs and then copy and paste the following code in it. This is going to be our product and in this class, we put all the attributes like SSD, RAM, USB, ProductName which are common to prepare a system(i.e. laptop or desktop). We also create one method (i.e. ShowProductInfo() ) which returns the System details.

    public class SystemDetails

    {

        public int RAM { get; set; }

        public int SSD { get; set; }

        public int HDD { get; set; }

        public string USB { get; set; }

        public string ProductName { get; set; }

 

        public string ShowProductInfo()

        {

            return "SystemName:  " + ProductName + " Contain these features " + RAM + " GB RAM, " + SSD + "GB SSD, " + HDD

                            + " GB HDD, " + USB + " USB " + ProductName + "]\n";

        }

    }


Step2: Creating Abstract Builder (SystemBuilder)
Create a class file with the name SystemBuilder.cs and then copy and paste the following in it. This SystemBuilder class is going to be an abstract class and will act as a blueprint for any subclasses that want to create a System. So, it will have different subclass implementations for different Systemtypes such as Laptop, Desktop,  etc. This class is having different abstract methods to Assign the RAM, HDD, SSD, USB, and SystemType.

public abstract class SystemBuilder

    {

            protected SystemDetails details;

 

            public void CreateBeverage()

            {

            details = new SystemDetails();

            }

            public SystemDetails GetBeverage()

            {

                return details;

            }

 

            public abstract void SetSystemType();

            public abstract void AssignRam();

            public abstract void AssignSSD();

            public abstract void AssignHDD();

            public abstract void AssignUSB();

       

    }


Step3: Creating Concrete Builder (LaptopBuilder and DesktopBuilder)

LaptopBuilder.cs

public class LaptopBuilder : SystemBuilder

    {

        public override void SetSystemType()

        {

            Console.WriteLine("Step 1 : Assign System Type");

            GetSystem().ProductName = "Laptop";

        }

 

        public override void AssignRam()

        {

            Console.WriteLine("Step 2 : Assign RAM");

            GetSystem().RAM = 32;

        }

        public override void AssignHDD()

        {

            Console.WriteLine("Step 3 : Assign HDD");

            GetSystem().HDD = 30;

        }

 

        public override void AssignSSD()

        {

            Console.WriteLine("Step 4 : Assign SSD");

            GetSystem().SSD = 8;

        }

 

        public override void AssignUSB()

        {

            Console.WriteLine("Step 5 : Assign USB");

            GetSystem().USB = "USB";

        }

    }

DesktopBuilder.cs

  public class DesktopBuilder : SystemBuilder

    {

        public override void SetSystemType()

        {

            Console.WriteLine("Step 1 : Assign System Type");

            GetSystem().ProductName = "Desktop";

        }

 

        public override void AssignRam()

        {

            Console.WriteLine("Step 2 : Assign RAM");

            GetSystem().RAM = 32;

        }

        public override void AssignHDD()

        {

            Console.WriteLine("Step 3 : Assign HDD");

            GetSystem().HDD = 30;

        }     

 

        public override void AssignSSD()

        {

            Console.WriteLine("Step 4 : Assign SSD");

            GetSystem().SSD = 8;

        }

 

        public override void AssignUSB()

        {

            Console.WriteLine("Step 5 : Assign USB");

            GetSystem().USB = "USB";

        }

 

       

   

    }

Step4: Creating the Director (SystemDirector)

Once you created the concrete builder classes, then you need to need to create the director. The director is the component that will execute the required steps in a particular order to create a beverage.

So, create a class file with the name SystemDirector.cs and then copy and paste the following code in it. This class is having one generic method which will take SystemBuilder as an input parameter and then create and return a particular System object.

    public class SystemDirector

    {

        public SystemDetails MakeSystem(SystemBuilder builder)

        {

            builder.CreateSystem();

            builder.SetSystemType();

            builder.AssignRam();

            builder.AssignHDD();

            builder.AssignSSD();

            builder.AssignUSB();

 

            return builder.GetSystem();

        }

    }


Step5: Client Code.

Now lets write below code in main method. Here, first, we will create an instance of the SystemDirector class and then create an instance of the LaptopBuilder class. Once we have the SystemDirector and LaptopBuilder instance, then we call the MakeSystem method on the SystemDirector instance bypassing the LaptopBuilder instance as an argument that will create and return the lptop. Again you need to follow the same process to make Desktop.

static void Main(string[] args)

        {

            SystemDetails details;

            SystemDirector director = new SystemDirector();

 

            LaptopBuilder tea = new LaptopBuilder();

            details = director.MakeSystem(tea);

            Console.WriteLine(details.ShowProductInfo());

            DesktopBuilder coffee = new DesktopBuilder();

            details = director.MakeSystem(coffee);

            Console.WriteLine(details.ShowProductInfo());

 

            Console.ReadLine();

        }


Output