Design Pattern

Creational Design Pattern in C#

 Creational design patterns are design patterns that deal with object creation mechanisms i.e. trying to create objects in a manner that is suitable to a given situation. The basic form of object creation could result in design problems or in added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

When to use the Creational Design Pattern?

In real-time applications, the project is created with a lot of classes. A lot of classes mean we are going to deal with a lot of objects. If these objects creations are scattered on the client code, then it leads to a lot of complicated logic at the client code. The Creational Design Pattern helps us to centralize the object creation logic.

The following design patterns belong to the Creational Design pattern category.

  1. Singleton Design Pattern
  2. Factory Design Pattern
  3. Abstract Factory Design Pattern
  4. Builder Design Pattern
  5. Fluent Interface Design Pattern
  6. Prototype Design Pattern
What is Singleton Pattern in C#?

When we need to ensures that only one instance of a particular class is going to be created and then provide simple global access to that instance for the entire application

What are the Advantages of using the Singleton Pattern in C#?

The Advantages of using the Singleton Design Pattern in C# are as follows.

  1. Takes care of concurrent access to the shared resource. That means if we are sharing a resource with multiple clients simultaneously, then concurrent access to that resource is well managed by the singleton design pattern.
  2. It can be lazy-loaded and also has Static Initialization.
  3. To share common data i.e. master data and configuration data which is not changed that frequently in an application. In that case, we need to cache the objects in memory.
  4. As it provides a single global point of access to a particular instance, so it is easy to maintain.
  5. To reduce the overhead of instantiating a heavy object again and again.
namespace SingletonDemo
    public sealed class Singleton
        private static int counter = 0;
        private static Singleton instance = null;
        public static Singleton GetInstance
                if (instance == null)
                    instance = new Singleton();
                return instance;
        private Singleton()
            Console.WriteLine("Counter Value " + counter.ToString());

        public void PrintDetails(string message)
Singleton fromTeachaer = Singleton.GetInstance;
 fromTeachaer.PrintDetails("From Teacher");
 Singleton fromStudent = Singleton.GetInstance;
 fromStudent.PrintDetails("From Student");
Some Real-time scenarios where you can use the Singleton Design Pattern:

Service Proxies: As we know invoking a Service API is an extensive operation in an application. The process that taking most of the time is creating the Service client in order to invoke the service API. If you create the Service proxy as Singleton then it will improve the performance of your application.

Facades: You can also create Database connections as Singleton which can improve the performance of the application.

Logs: In an application, performing the I/O operation on a file is an expensive operation. If you create your Logger as Singleton then it will improve the performance of the I/O operation.

Data sharing: If you have any constant values or configuration values then you can keep these values in Singleton So that these can be read by other components of the application.

Caching: As we know fetching the data from a database is a time-consuming process. In your application, you can cache the master and configuration in memory which will avoid the DB calls. In such situations, the Singleton class can be used to handle the caching with thread synchronization in an efficient manner which drastically improves the performance of the application. 

What are the Disadvantages of using the Singleton Design Pattern in C#?

Unit testing is very difficult because it introduces a global state into an application.

It reduces the potential for parallelism within a program because to access the singleton instance in a multi-threaded environment, you need to serialize the object by using locking

Why Singleton Class sealed in C#?

Let’s move the DerivedSingleton class inside the Singleton class. When we move the DerivedSingleton class within the main Singleton class, then it becomes a nested class or you can say a child class of the main singleton class as shown below.

Now if you run the application then you will see the following output.

Why Singleton Class Sealed in C#

The above output clearly shows that the counter value has incremented to 2 which proves that the private constructor executed twice and hence it creates multiple instances of the singleton class. So, by removing the sealed keyword we can inherit the singleton class, and also possible to create multiple objects of the singleton class. This violates singleton design principles.

Let’s make the Singleton class as sealed as shown below and then compiled the program and see what happens.

Thread-safe Singleton Design Pattern in C# with Examples

So, now run the application and it will give you the following output.

Thread-safe Singleton Design Pattern in C#
What is Lazy or Deferred Loading in C#?

The Lazy or Deferred Loading is a design pattern or you can say its a concept which is commonly used to delay the initialization of an object until the point at which it is needed. So the main objective of Lazy loading is to load the object on-demand or you can say object when needed. The most important point that you need to keep in mind is that, you need to use the Lazy loading when the cost of the object creation is very high as well as the use of that object is very rare. The lazy loading improves the performance of an application if it is used properly. We can use the Lazy keyword to make the singleton instance as lazy loading. 

What are the similarities between Singleton and Static class in C#?

  1. Both static class and singleton class can have only one instance of a copy that is available in memory throughout the whole application. They both are used for holding the global state of an application.
  2. Both static classes and singleton classes can be implemented as thread-safe.

Factory Design Pattern in C#

“A factory is an object which is used for creating other objects”. In technical terms, we can say that a factory is a class with a method. That method will create and return different types of objects based on the input parameter, it received.

In the Factory Design pattern, we create an object without exposing the creation logic to the client and the client will refer to the newly created object using a common interface.

In simple words, if we have a superclass and n number of subclasses, and based on the data provided, if we have to create and return the object of one of the subclasses, then we need to use the factory design pattern.

The basic principle behind the factory design pattern is that, at run time, we get an object of similar type based on the parameter we pass. 

Factory Design Pattern Implementation in C#

Now the client needs to create the object through CreditCardFactory. For example, if the client wants to create the instance of Platinum Credit then he/she needs to do something like below. As you can see, he/she needs to pass the Credit card type to the GetCreditcard method of the CreditCardFactory class. Now, the GetCreditcard() method will create a Platinum class instance and return that instance to the client.

C# Factory Pattern example
Real-Life Example of Factory Pattern:

From Lehman’s point of view, we can say that a factory is a place where products are created. In order words, we can say that it is a centralized place for creating products. Later, based on the order, it received, the appropriate product is delivered by the factory.

For example, a car factory can produce different types of cars. If you are ordering a car to the car factory, then based on your requirements or specifications, the factory will create the appropriate car and then delivered that car to you.

The same thing also happens in the factory design pattern. A factory (i.e. a class) will create and deliver products (i.e. objects) based on the incoming parameters.

When to use the Factory Design Pattern in real-time applications?

It would not be a good programming approach to specify the exact class name while creating the objects by the client which leads to tight coupling between the client and the product. To overcome this problem, we need to use the Factory Design Pattern in C#.

This design pattern provides the client with a simple mechanism to create the object. So, we need to use the Factory Design Pattern in C# when

  1. The Object needs to be extended to the subclasses
  2. Classes don’t know what exact sub-classes it has to create
  3. The Product implementation going to change over time and the Client remains unchanged
Problems of Simple Factory Pattern in C#
  1. If we need to add any new product (i.e. new credit card) then we need to add a new if else condition in the GetCreditCard method of the CreditCardFactory class. This violates the open/closed design principle.
  2. We also have a tight coupling between the Factory (CreditCardFactory) class and product classes (MoneyBack, Titanium, and Platinum).

What is the Builder Design Pattern?

The Builder Design Pattern builds a complex object using many simple objects and using a step-by-step approach. The Process of constructing a complex object should be generic so that the same construction process can be used to create different representations of the same complex object.

So, the Builder Design Pattern is all about separating the construction process from its representation. When the construction process of your object is very complex then only you need to use to Builder Design Pattern. If this is not clear at the moment then don’t worry we will try to understand this with an example.

Please have a look at the following diagram. Here, Laptop is a complex object. In order to build a laptop, we have to use many small objects like LCD Display, USB Ports, Wireless, Hard Drive, Pointing Device, Battery, Memory, DVD/CD Reader, Keyboard, Plastic Case, etc. So, we have to assemble these small objects to build laptop complex objects.

What is the Builder Design Pattern?
Understanding the Builder Design Pattern with one real-time example:

Let us understand the builder design pattern with one real-time example. Suppose we want to develop an application for displaying the reports. The reports we need to display either in Excel or in PDF format. That means, we have two types of representation of my reports. In order to understand this better, please have a look at the following diagram.

Builder Design Pattern in C# with Examples

Understanding the Class Diagram of Builder Design Pattern in C#

Class Diagram of Builder Design Pattern in C#