December 5, 2024
adapter-pattern

Adapter Pattern

Adapter design pattern allows incompatible classes to work together by converting the interface of one class into another. It’s like a translator. When two heads of countries who don’t speak a common language meet, usually an interpreter sits between them and translates the conversation, thus enabling communication.

Let’s think, we have two classes. One take array input, another one provide a list as output. Now if we want to work together then we need an adapter.

public class Calculator
 {
        public int GetSum(int[] numbers)
        {
            int sum = numbers.Sum();
            return sum;
        }
 }
public class CalculatorAdapter
 {
        private readonly Calculator _calculator;
        public CalculatorAdapter()
        {
            _calculator =new Calculator();
        }
 
        public int GetTotalSum(List numbers)
        {
            int sum = _calculator.GetSum(numbers.ToArray());
            return sum;
        }
 }

Here CalculatorAdapter class is an adapter. Our corresponding client code is:

class Program
 {
        static void Main(string[] args)
        {
            CalculatorAdapter calculator = new CalculatorAdapter();
            List numbers = new List { 1, 2, 3, 4, 5 };
            var sum = calculator.GetTotalSum(numbers);
            Console.WriteLine(sum);
        }
 }

We need to choose the adapter design pattern in our applications when:

  • A class needs to be reused that does not have an interface that a client requires.
  • Allow a system to use classes of another system that is incompatible with it.
  • Allow communication between a new and already existing system which are independent of each other.

Rashedul Alam

I am a software engineer/architect, technology enthusiast, technology coach, blogger, travel photographer. I like to share my knowledge and technical stuff with others.

View all posts by Rashedul Alam →

One thought on “Adapter Pattern

Leave a Reply

Your email address will not be published. Required fields are marked *