Design Pattern – Adapter

C# CONCEPTS

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.

Photo by Brett Sayles from Pexels

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

  • Basic knowledge of OOPS concepts.
  • Any programming language knowledge.

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

View at Medium.com

Learning Objectives

  • 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.”

https://gist.github.com/ssukhpinder/aff5f843fcdf5310947db30fbf2886ca

Secondly, let’s create a target interface.

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

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

https://gist.github.com/ssukhpinder/a76091b2bfc23d8a0ebcbcf2c0a7b68f

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

https://gist.github.com/ssukhpinder/c11c1cea83b055c971e98632567a2962

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.

View at Medium.com

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.

More design patterns — Reference Linkedin Learning

View at Medium.comView at Medium.comView at Medium.com

Leave a comment