Design Pattern – Adapter

#Aspnetcore #AdapterDesignPattern #Csharp #DesignPatterns #Dotnet

According to Gang of Four, the Adapter Pattern converts the interfaces of a class into interfaces that the client requires.

In other words, the adapter design pattern helps incompatible interfaces work collectively.


Use Case

Let’s consider an example of two organizations merging; X organization is taking over Y, but while combining code, the interfaces are not compatible. Assume that interface that provides a list of transactions of organization Y is not compatible with X.

So the adapter design pattern helps solve this problem whose implementation is very straightforward.


Prerequisites

  1. Basic knowledge of OOPS concepts.

  2. Any programming language knowledge.

The article demonstrates the usage of adapter design patterns using the C# programming language. So, to begin with, C#

https://medium.com/c-sharp-progarmming/introduction-to-c-222567161964


Learning Objectives

  1. How to code using an adapter design pattern?



Getting Started

Let’s create a list of transactions from organization Y that are converted to patterns that the client application of organization X requires. The above class is known as “Adaptee.”

public class OrgYTransactions
{
    public List<string> GetTransactionsList()
    {
        List<string> transactions = new List<string>();
        transactions.Add("Debit 1");
        transactions.Add("Debit 2");
        transactions.Add("Debit 3");
        return transactions;
    }
}

Secondly, let’s create a target interface.

public interface ITransactions{
  List<string> GetTransactions();
}

Now finally, let’s implement the adapter class as follows.

public class TransAdapter : OrgYTransactions, ITransactions
{
    public List<string> GetTransactions()
    {
        return GetTransactionsList();
    }
}

After all the above implementations are done, let’s understand how to use the adapter class in a console application.

class Program
{
    static void Main(string[] args)
    {
        ITransactions adapter = new TransAdapter();
        foreach (var item in adapter.GetTransactions())
        {
            Console.WriteLine(item);
        }
    }
} 

If you look closely at the below usage, we have used the target interface ITransactions and the adapter class TransAdapter without considering how third-party class OrgYTransactions interfaces look. That’s the power of the adapter design pattern that it converts the interfaces of a class into interfaces that the client requires.

Github Repo

The following repository shows the above use case implementation using an Adapter Design Pattern in the console-based application.

https://github.com/ssukhpinder/AdapterPattern





Thank you for reading, and I hope you liked the article. Please provide your feedback in the comment section.


Follow me on

C# Publication, LinkedIn, Twitter, Dev.to, Pinterest, Substack, Wix.