Monday, April 22, 2024

Mediator Design Pattern in C#

The Mediator Design Pattern is a behavioral design pattern that promotes loose coupling between objects by encapsulating how they interact. It centralizes complex communication logic between multiple objects into a mediator object, thus reducing direct dependencies between them. This promotes easier maintenance and scalability of the system.

The Mediator Design Pattern restricts direct communications between the objects and forces them to collaborate only via a mediator object. This pattern is used to centralize complex communications and control between related objects in a system. The Mediator object acts as the communication center for all objects. That means when an object needs to communicate with another object, it does not call the other object directly. Instead, it calls the mediator object, and it is the responsibility of the mediator object to route the message to the destination object.

Components of Mediator Design Pattern

  1. Mediator: Defines an interface for communication between colleague objects.
  2. Colleague: It is an abstract class, and Concrete Colleague classes will implement this abstract class.
  3. ConcreteMediator: Implements the mediator interface, coordinating communication between colleague objects.
  4. ConcreteColleague: Implements the colleague interface and communicates with other colleagues through the mediator.

Sunday, April 14, 2024

Template Method Design Pattern in C#

The Template Method Design Pattern is a behavioral design pattern that defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure. It allows reusing common behavior across multiple classes while still allowing customization where necessary.

Components of Template Method Design Pattern

  • Abstract Class: This class defines the template method, which is the skeleton of the algorithm. It consists of several abstract methods that subclasses must implement.
  • Concrete Classes: These classes inherit from the abstract class and provide implementations for the abstract methods.

Monday, April 8, 2024

Command Design Pattern in C#

The Command Design Pattern is a behavioral design pattern that encapsulates a request as an object, thereby allowing parameterization of clients with queues, requests, and operations. This pattern decouples sender and receiver of a request based on a command, which helps in invoking the right method at the right time without knowing the actual implementation details.

Components of Command Design Pattern

  1. Command: Defines an interface for executing an operation.
  2. Concrete Command: Implements the Command interface and binds a receiver with an action. It defines a binding between the action and the receiver.
  3. Invoker: Requests the command to execute the operation.
  4. Receiver: Knows how to perform the operation.

Monday, April 1, 2024

Strategy Design Pattern in C#

The Strategy Design Pattern is a Behavioral Design Pattern that enables selecting an algorithm’s behavior at runtime. Instead of implementing a single algorithm directly, run-time instructions specify which of a family of algorithms to use.

This pattern is ideal when you need to switch between different algorithms or actions in an object dynamically. That means the Strategy Design Pattern is used when we have multiple algorithms (solutions) for a specific task, and the client decides which algorithm to use at runtime.

Components of Strategy Design Pattern

  1. Strategy Interface: This defines a set of methods that represent the algorithms. It acts as a contract for all concrete strategy classes.
  2. Concrete Strategies: These are the actual implementations of the algorithms defined in the strategy interface.
  3. Context: This is the class that uses the strategy. It contains a reference to the strategy interface and can switch between different strategies dynamically.

Sunday, March 24, 2024

Observer Design Pattern in C#

The Observer Design Pattern is a behavioral design pattern that defines a one-to-many dependency between objects. When one object (the subject) changes its state, all its dependents (observers) are notified and updated automatically. This pattern is widely used in software engineering to establish communication between objects in a loosely coupled manner.

This Design Pattern is widely used for implementing distributed event-handling systems where an object needs to notify other objects about its state changes without knowing who these objects are.

In the Observer Design Pattern, an object (called a Subject) maintains a list of its dependents (called Observers). It notifies them automatically whenever any state changes by calling one of their methods. The Other names of this pattern are Producer/Consumer and Publish/Subscribe.

Components of Bridge Design Pattern

  1. Subject: This is the object that is being observed. It maintains a list of observers and provides methods to attach, detach, and notify observers of state changes.
  2. Observer: This is the interface that defines the method(s) that the subject will use to notify observers of state changes.
  3. ConcreteSubject: This is the concrete implementation of the subject. It maintains the state of interest and notifies observers when changes occur.
  4. ConcreteObserver: This is the concrete implementation of the observer. It registers itself with the subject and implements the update method to react to changes in the subject's state.

Thursday, January 25, 2024

Bridge Design Pattern in C#

The Bridge Design Pattern is a structural pattern that separates the abstraction from its implementation so that the two can vary independently.This pattern involves an interface that acts as a bridge between the abstraction class and implementer classes. It is useful in scenarios where an abstraction can have several implementations, and you want to separate the implementation details from the abstraction.

Purpose of Bridge Pattern

  • Decouple an abstraction from its implementation so that the two can vary independently.
  • Promote code reusability by allowing the abstraction and implementation to evolve independently.

Sunday, January 21, 2024

Flyweight Design Pattern in C#

The Flyweight design pattern is a structural pattern that focuses on minimizing the memory footprint or computational expenses of an object. It achieves this by sharing as much as possible with related objects, rather than keeping all of the data in each object. This is particularly useful when dealing with a large number of similar objects, as it helps reduce the overall memory consumption and improves performance.

Purpose of Flyweight Pattern:

  • To reduce the number of objects and to conserve memory by sharing objects among multiple contexts.
  • To achieve performance improvement by minimizing the overhead of creating and managing large numbers of similar objects.

Saturday, January 13, 2024

Proxy Design Pattern in C#

The Proxy Design Pattern is a structural design pattern. that provides a surrogate or placeholder for another object to control access to it.

This pattern comes in handy when we want to add an extra layer of control over the access to an object, such as lazy loading, access control, or logging. In C#, the Proxy Design Pattern is commonly used to create a surrogate object that represents another object.

We can also say that the Proxy is the object the client calls to access the real object behind the scene. Proxy means in place of or on behalf of. That means, In the Proxy Design Pattern, a class represents the functionality of another class.

Component of Proxy Design pattern

  • Subject: This is an interface that defines the members that will be implemented by the RealSubject and Proxy class so that the Proxy can be used by the client instead of the RealSubject. In our example, it is the ISharedFolder interface.
  • RealSubject: This is a class that we want to use more efficiently by using the proxy class. This class should implement the Subject Interface. In our example, it is the SharedFolder class.

Friday, January 12, 2024

Composite Design Pattern in C#

The Composite Pattern is a structural design pattern that enables us to treat individual and group objects uniformly by creating a hierarchical (tree-like) structure of objects, where both the composite (groups) objects and leaf (individual) objects share a standard interface.

This pattern lets clients treat individual objects and compositions of objects uniformly. That means the client can access the individual objects or the composition of objects in a uniform manner. It’s useful for representing hierarchical structures such as file systems, UI components, or organizational structures.

What are Composite and Leaf classes?

  1. The Composite Class — represents a group of objects and can contain other objects (i.e. env_item_collection, env_item_collection_parent, env_root), and
  2. the Leaf Class — represents an individual object that cannot contain other objects (i.e. env_item).

Monday, January 8, 2024

Facade Design Pattern in C#

Facade is a structural design pattern that provides a simplified interface to a library, a framework, or any other complex set of classes.It helps encapsulate the complexity of multiple subsystems into a single unified interface.

In software terms, Facade pattern hides the complexities of the systems and provides a simple interface to the clients.

This pattern involves one wrapper class which contains a set of methods available for the client. This pattern is particularly used when a system is very complex or difficult to understand and when the system has multiple subsystems.

Component of Facade Design Pattern

  • Complex System: A library of subsystems.
  • Subsystems: These are classes within a complex system and offer detailed operations.
  • Façade: This is a wrapper class which wrapper class which contains a set of members which are required by the client.
  • Client: This is a class which calls the high-level operations in the Façade.

Tuesday, January 2, 2024

Decorator Design Pattern in C#

The Decorator Design Pattern is a structural pattern in software development that allows behavior to be added to individual objects, either statically or dynamically, without affecting the behavior of other objects from the same class.

The idea of the Decorator Pattern is to wrap an existing class, add other functionality to it, then expose the same interface to the outside world. Because of this our decorator exactly looks like the original class to the people who are using it.

It is used to extend or alter the functionality at runtime. It does this by wrapping them in an object of the decorator class without modifying the original object. So it can be called a wrapper pattern.

Components of Decorator Design Pattern

  • Component: It defines the interface of the actual object that needs functionality to be added dynamically to the ConcreteComponents.
  • ConcreteComponent: The actual object in which the functionalities could be added dynamically.
  • Decorator: This defines the interface for all the dynamic functionalities that can be added to the ConcreteComponent.
  • ConcreteDecorator: All the functionalities that can be added to the ConcreteComponent. Each needed functionality will be one ConcreteDecorator class.

Friday, December 29, 2023

Adapter Design Pattern in C#

The Adapter Design Pattern is a structural pattern that allows incompatible interfaces to work together. It acts as a bridge between two incompatible interfaces, enabling them to collaborate seamlessly without modifying their existing code.The adapter plays the role of converter or translator.

This pattern is particularly useful when integrating new components or systems that have different interfaces from the ones already in use.

To handle the incompatibility, we use different approaches, and based on that, we can classify the Adapter Pattern into 2 parts.

  • Object Adapter Pattern
  • Class Adapter Pattern

Monday, December 11, 2023

Prototype Design Pattern in C#

What is Prototype Design Pattern?

The prototype design pattern is a creational design pattern that allows creating new objects by cloning an existing object. This pattern is useful when the creation of an object is costly or complex, and we want to avoid repeating the same process for each new instance. By using the prototype pattern, we can create new objects by copying the properties and behaviors of an existing object, and then modifying them as needed.

One of the benefits of the prototype pattern is that it reduces the dependency on subclasses and factory methods. Instead of creating objects using specific constructors or factory methods, we can use a generic prototype object that can be cloned and customized. This makes the code more flexible and extensible, as we can add new types of objects without changing the existing code.

Components of Prototype Pattern

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

Monday, December 4, 2023

Builder Design Pattern in C#

What is the Builder Design Pattern?

The Builder Design Pattern is a creational design pattern that helps in constructing complex objects step by step. It separates the construction of an object from its representation, allowing the same construction process to create different representations. In C#, the Builder pattern is widely used to create objects with varying configurations while keeping the construction process unchanged.

The key idea is to separate the construction of a complex object from its representation, allowing the same construction process to create different representations.

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, only you need to use the Builder Design Pattern.

COmponents of Builder Design Pattern

  • Abstract Builder: The Builder is an interface defining all the steps to make the concrete product.
  • Concrete Builder: The Concrete Builder Classes implements the Abstract Builder interface and provides implementation to all the abstract methods. The Concrete Builder is responsible for constructing and assembling the individual parts of the product by implementing the Builder interface. It also defines and tracks the representation it creates.
  • Director: The Director takes those individual processes from the Builder and defines the sequence to build the product.
  • Product: The Product is a class, and we want to create this product object using the builder design pattern. This class defines different parts that will make the product.

Sunday, November 5, 2023

Abstract Factory Design Pattern in C#

In this article, I will explain the Abstract Factory Design Pattern in C# with practical examples. I encourage you to check out our previous article, which covers the Factory Design Pattern in C# along with an example.The Abstract Factory Design Pattern falls under the category of creational design patterns and is widely applied in real-world software development. In this article, we'll explore the following topics

What is the Abstract Factory Design Pattern?

The Abstract Factory Design Pattern is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes. It is a higher-level pattern than the Factory Method pattern, which deals with creating individual objects, while the Abstract Factory creates families of objects.

"Abstract" means hiding details, "Factory" refers to the entity that creates things, and "Pattern" indicates a design approach. Therefore, the Abstract Factory Pattern is a method in software design that allows you to wrap a set of factories with a shared theme.

Put simply, the Abstract Factory serves as a high-level factory that generates other factories. It's often referred to as the "Factory of Factories." This design pattern, the Abstract Factory, offers a way to create groups of related products without specifying the actual objects to be created.

Sunday, October 22, 2023

Factory Method Design Pattern in C#

The Factory Method Design Pattern belongs to the Creational Design Pattern Category.As part of this article, we will discuss this design pattern in detail with example

What is Factory Method Design Pattern

As per Gang of Four, the Factory Method Design Pattern states that Defines an interface for creating an object but lets the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.

In simple words, The Factory Method Design Pattern is used when we create the object without exposing the object creation logic to the client. In the factory method design pattern, we will create an abstract class as the Factory class, which will create and return the product instance, but it will let the subclasses decide which class to instantiate.

The Key Components:

  1. Factory Interface/Abstract Class:This serves as a blueprint for an interface or an abstract class that contains a method for creating objects. Typically, this method is named something like 'createProduct()' or 'factoryMethod()'.
  2. Concrete Factories:These are tangible classes that implement the factory interface. They provide specific implementations of the 'createProduct()' method. Each concrete factory is responsible for producing a particular type of product.
  3. Product Interface/Abstract Class:This defines an interface or an abstract class for the products generated by the factories. Product classes usually share common attributes or methods.
  4. Concrete Products:These are the real-deal classes that implement the product interface. Each concrete product embodies a specific type of object.

Sunday, October 1, 2023

Factory Design Pattern in C#

The Factory Design Pattern is one of the most frequently used design patterns in real-time applications. The Factory Design Pattern in C# falls under the Creational Design Patterns Category.

What is Factory Design Pattern in C#?

Let us first try to understand the definitions of the factory design pattern.

According to Gang of Four (GoF), the Factory Design Pattern states that A factory is an object 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 objects based on the received input parameter.

In simple words, when we have a main class(super class) and several different types of classes(subclasses) that are related to it, and we want to make an object from one of these related classes based on some information, we use something called the Factory Design Pattern in C#.

The Key Components:

  1. Product Interface/Abstract Class:This defines an interface or an abstract class for the products generated by the factories. Product classes usually share common attributes or methods.
  2. Concrete Products:These are the real-deal classes that implement the product interface. Each concrete product embodies a specific type of object.
  3. Factory Class:This class contains a method for creating objects.Typically, this method is named something like 'createProduct()' or 'factoryMethod()'.

Sunday, September 10, 2023

Thread-Safe Singleton Design Pattern in C#

In this post, we are going to discuss How to Implement Thread-Safe Singleton Design Pattern in C# with Examples. Please read our previous article where we discussed Singleton Design Pattern. In that post, the way we have implemented the Singleton Design Pattern is not Thread Safe in a Multithread Environment.

Understand Thread-Safe in Singleton Design Pattern in C#.

Before deep dive in to Thread-Safe Singleton Pattern, let us first see the problem that we face in a multithread environment if the Singleton Class is not Thread-Safe. Below is the Singleton Class which we have created in our last post.

    /// <summary>
    /// Sealed class to ensure that it cannot be inherited
    /// </summary>
    public sealed class Singleton
    {
        /// <summary>
        /// To store the Singleton Instance
        /// </summary>
        private static Singleton instance = null;

        /// <summary>
        /// Counter value will be increment by 1 each time the object of the class is created
        /// </summary>
        private static int counter = 0;

        /// <summary>
        /// Private constructor to restrict the class to be instantiated from outside the class
        /// </summary>
        private Singleton()
        {
            counter++;
            Console.WriteLine("Counter Value " + counter.ToString());
        }

        /// <summary>
        /// Static Method to return the Singleton Instance
        /// </summary>
        public static Singleton Instance()
        {
            if (instance == null) { instance = new Singleton(); }
            return instance;
        }

        /// <summary>
        /// Method to accessed from outside of the class by using the Singleton Instance
        /// </summary>
        /// <param name="message"></param>
        public void PrintDetails(string message)
        {
            Console.WriteLine(message);
        }
    }

Let’s modify the Program.cs as follows to use multithread programming. As you can see in the below code, we are using Parallel.Invoke method and call PrintCoachDetails() and PrintPlayerDetails() methods parallelly.

Parallel.Invoke(() => PrintCoachDetails(),
                () => PrintPlayerDetails());

Console.ReadLine();

static void PrintCoachDetails()
{
    //Thread-1 Calling the GetInstance() Method of the Singleton class
    Singleton fromCoach = Singleton.Instance();
    fromCoach.PrintDetails("From Coach");
}
static void PrintPlayerDetails()
{
    //At the same time, Thread-2 also Calling the GetInstance() Method of the Singleton Class
    Singleton fromPlayer = Singleton.Instance();
    fromPlayer.PrintDetails("From Player");
}

So in above example, we are using the Parallel.Invoke method to access the Instance() Method parallelly. That means at the same time multiple threads are accessing the Instance() Method. The above code is not Thread-Safe because the way we have written the code here two different threads can evaluate the condition if (instance == null) at the same time and both threads found it to be true and they both will create the instances, which violates the singleton design pattern. So, now run the application and it will give you the following output.

singleton design pattern

The above output clearly shows that the counter value has incremented to 2, which proves that the constructor of the Singleton class is executed two times as a result two instances of the singleton class have been created. So, if the Singleton class is not Thread-Safe, then we may end up creating multiple instances of the Singleton class in a Multithread Environment.

Thursday, August 31, 2023

Singleton Design Pattern in C#

The Singleton design pattern stands as one of the most commonly used creation patterns in software development. It guarantees that a class exists in only one instance and grants a universal way to reach that instance. This proves especially handy when aiming to establish a singular hub of control or coordination within your application. Let's explore the Singleton pattern through a practical C# example.

What is Singleton Pattern?

We need to use the Singleton Design Pattern in C# when we need to ensure 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. This pattern becomes invaluable when handling resources like database connections, thread pools, configuration settings, and more—minus the complication of creating numerous instances.

Implementation Guidelines of Singleton Design Pattern

Following are the guidelines to implement the Singleton Design Pattern

  1. Declare a constructor that should be private and parameterless. This is required to restrict the class to be instantiated from outside the class.
  2. The class should be declared as sealed which will ensure that it cannot be inherited.
  3. We need to create a private static variable that is going to hold a reference to the singleton instance of the class.
  4. We also need to create a public static property/method which will return the singleton instance of the class.

Implement the Singleton Pattern in C#

There are many ways, we can implement the Singleton Design Pattern in C#. They are as follows.

  1. No Thread-Safe Singleton Design Pattern
  2. Thread-Safety Singleton Implementation using Lock.
  3. Implementing Thread-Safety Singleton Design Pattern using Double-Check Locking.
  4. Using Eager Loading to Implement Thread-Safety Singleton Design Pattern.
  5. Using Lazy<T> Generic Class to Implement Lazy Loading in Singleton Design Pattern.

Wednesday, August 23, 2023

Design Patterns: Building Robust and Flexible Software

What Are Design Patterns?

At their core, design patterns are proven solutions to recurring design problems. They offer developers a common vocabulary and a set of guidelines to approach and tackle issues that frequently arise during software development. These patterns are not specific to a particular programming language or framework; rather, they provide general templates that can be adapted to different contexts.

Why Do Design Patterns Matter?

1.Code Reusability: Design patterns encapsulate solutions to common problems. By using these patterns, developers can reuse tried-and-tested solutions, saving time and reducing the likelihood of bugs.

2.Scalability and Maintainability: Implementing design patterns leads to cleaner, more organized code that is easier to understand and maintain. This is crucial as projects grow in complexity.

3.Communication: Design patterns offer a common language for developers to discuss and document solutions. This leads to better collaboration within teams and across different projects.

4.Flexibility: Design patterns promote loosely coupled components, allowing you to swap out parts of your system without causing cascading changes.

^ Scroll to Top