Adapter Design Pattern

In my last post, I discussed one of the creational design patterns now will discuss the adapter design pattern which is a structural design pattern.

Before moving further if you would like to understand the basic concept and type of design pattern refer to my previous post on Singleton Design Pattern in which I discuss basic concept and type of design pattern very high level. So that will help you to get a better understanding of the adapter design pattern.

As per the gang of four definition adapter design pattern “Match interfaces of different classes

In software engineering adapter pattern allows the incompatible class to interact with the existing class by converting the interface of one class into an interface expected by the client. Adapter pattern help to reuse the existing functionality as it is a bridge between two incompatible interfaces.

Adapters coverts the interface of one class into an interface a client expects

Let’s take a real-life example, Travelling internationally with electronic devices has become so common and the power plug and socket standard are different in different countries so you need an adapter to convert the shape of your home power plugs to the shape of the outlets in the region of the world you are traveling to.

Untitled Diagram

Now let’s take one technical example, your current application work with XML data and now you are going to plug in some external APIs to your application but that external APIs work with JSON data only. In this situation, you can either rewrite your code to support JSON data or you can ask third-party APIs providers to change their code to support XML. The first option required lots of effort and regression testing as you are going to change your existing code and the second option might be not possible as they are not supporting XML data.

To solve this problem you can create an adapter interface that is responsible to convert one type of object to an incompatible type of object. In our scenario, we can create XML to JSON adapter which will convert XML data to JSON data, and then it will pass to third-party APIs. It is also possible to create a two-way adaptor that converts the call in both directions. following diagram shows how we can implement XML to JSON adapter in our example

AdapterDesignPattern

Let’s take one more example in which we will going to implement the actual code and using that code we will try to understand the adapter design pattern. you can find same code from Github: Adapter Design Pattern Example

Scenario: We have a product display service that can be display product from two different sources one using file and another by calling the vendor API

So, for the above scenario, we are going to create an IProductSourceAdapter Interface which has Task<IEnumerable<Product>> GetProducts(); So, the client will use this method to get the list of products.

Also, we are going to implement two different classes. One class for file FileSource which get the product from a file using GetProductFromFile method and another for API VendorApiSourcewhich get products by calling Vendor API under GetProducts method

Now, we are going to implement FileSourceAdapter which create an instance of ​​FileSource and delegate the call to FileSource.GetProductFromFile(_filePath)

In the same way, we are going to implement VendorSourceAdapter which create an instance of VendorApiSourceand delegate the call to VendorApiSource.GetProducts(_clientApiUrl)

Now, here our client ProductDisplayService inject IProductSourceAdapterwe don’t care about which particular implementation it is. we will get this information based on the type that gets injected.

AdapterDesignPatternNew

  • Step 1: Client which has existing business logic.
  • Step 2: Client Interface describes a protocol that other classes must follow to be able to collaborate with the client code.
  • Step 3: Service has its own logic. The client can’t use this class directly because it has an incompatible interface.
  • Step 4: Adapter is receiving a call from the client via client interface and translate calls to the service class

Adapter design pattern follows Single responsibility principle as each service has its own logic and only responsible for one thing like FileSource getting a product from a file only. Adapter design pattern also follows the Open-Closed principle as you can bring a new type of source without breaking the existing client code.

Also, you can find source code which demonstrate above example from following github link

https://github.com/nibro7778/adapter-design-pattern

Hope you’ll like it!

Singleton Design Patterns

Before discussing singleton design pattern let me give you some basic background of design pattern and its history

The idea of design pattern was picked by four authors: Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm, very well known by the Gang of Four where they applied a concept of typical programming. They came up with 23 design pattern for solving various real-life problems of object-oriented design.

A design pattern is one kind of recipes book to deliver delicious and tasty programming dishes 😉 A Design pattern act as a template which can be applied to the real world problem

Writing a code using design pattern makes your code more reliable, scalable and maintainable

There are 3 type of design pattern

  • Creational
  • Structural
  • Behavioral

Creational: This design pattern gives you the functionality of object creation and initialization based on different cases. most popular creational design pattern are Factory, Singleton

Structural: This type of design pattern is responsible for building simple and efficient class hierarchies and a relation between different classes. for example Adapter, bridge

Behavioural: This design pattern deals with communication between classes and objects. for example Chain of Responsibility, Command, Interpreter etc

Singleton Design Pattern

Singleton design pattern is a creational design pattern which let you ensure that only single object is created for a particular class. All further references to the class are referred to this object.

Now, you think then what is different between static and singleton. the main difference between those two is singleton provide you object whereas static classes provide you with a static method. Singleton can implements interfaces, inherit from other classes and it is aligned with the object-oriented concept. Also, a singleton object can be passed to other methods as a reference whereas a static object cannot be passed as a reference.

For implementing singleton pattern to your code you must consider two common steps

  1. Making default constructor as a private so that it cannot be instantiated outside of the class.
  2. Create public creator method, which will create an object using a private constructor and save it on a static variable. so whenever any user requested for the object using public creator method it will return cached object from a static variable.

Top level view of a singleton design pattern class diagram

SingletonDesign

Following is sample code which ensures you only one object of the class is created and provide you access to that object using GetInstance() method.

public class Singleton {
        /// <summary>
        /// Static field to stored instance of the singleton class
        /// </summary>
        private static Singleton _instance;

         /// <summary>
         /// Private construct to restrict user to instance outside the class
         /// </summary>
         private Singleton() { }

         /// <summary>
         /// GetInstance method which create new instance if its null, and return instance  
         /// </summary>
         public static Singleton GetInstance => _instance ?? (_instance = new Singleton());
}

Following are some of the example of a real-world scenario where we can use singleton design pattern

  • Logging management
  • Device management
  • File management
  • Application configuration management
  • Cache management
  • Session-based shopping cart management

I have implemented a small project which demonstrates how we can use the singleton pattern for Logging to file or to external resources. find below git repository link for this.

Github: Singleton Pattern Example

Circuit Breaker Design Pattern

Most of the enterprise application uses external services to make an external operation like sending Email or SMS to send notification or external API, external resources to add functionality to our application. Whenever we are making a call to those external services, there may be a chance that those services are down. Our application should be prepared to handle that kind of scenario. We can handle this kind of scenario using retry pattern but retry pattern assumes that external service is available and continues to make a request

The circuit breaker pattern has different than a retry pattern. The circuit breaker prevents an application to perform an external services call that is likely to fail.

This pattern has three operation state:

  • Close state
  • Open state
  • Half Open state

Close State: Operation are executed as usual (whenever we are making the first call to the external services at the time it will be in the closed state)

  •  If a call to external service fails: The failure count is incremented and an OperationFailedException is thrown. If the failure count exceeds the threshold, the circuit breaker trips into the “open” state.
  • If a call to external service succeeds: if calls succeed before the threshold is reached, the failure counter is reset and operation are executed as usual

Open state: whenever circuit breaker is in open state all calls to the external services will fail and In this state, it will not make an actual call to the external services instead of it will throw an exception OpenStateException. A timeout is started when the circuit breaker trips.

Once the timeout is reached, the circuit breaker enter into the half state

Half state: In “half state” circuit breaker allows one operation to execute.

  •  If a call to external service fails: the circuit breaker re-enter into open state and timeout is reset.
  • If a call to external service succeeds: circuit broker enters into close state and operations are executed as usual

CircuitBroker

Below sample code will be used to implement circuit breaker with Polly. Here we are creating the Polly handler for circuit breaker when WebException occurred during an external call. This policy will break the circuit with two consecutive exceptions of WebExcption type and the circuit will remain a broker

//creating policy object for handle webexception using circuit breaker
Policy policy = Policy.Handle() 
  .CircuitBreaker(
    exceptionsAllowedBeforeBreaking: 2, 
    durationOfBreak: TimeSpan.FromMinutes(1) );

//To Excute external service call
policy.Execute(action); 

For a better understanding of the circuit breaker using Polly, you can check it out on below link

https://github.com/App-vNext/Polly/wiki/Circuit-Breaker

I have also created sample repo in GitHub to provide you a basic understanding to implement circuit breaker with Polly nuget package. GitHub demo-application-circuit-breaker