adapter-pattern

Adapter design sample permits incompatible courses to work collectively by changing the interface of 1 class into one other. It’s like a translator. When two heads of nations who don’t communicate a standard language meet, normally an interpreter sits between them and interprets the dialog, thus enabling communication.

Let’s suppose, now we have two courses. One take array enter, one other one present an inventory as output. Now if we wish to work collectively then we’d like an adapter.

public class Calculator
 {
        public int GetSum(int[] numbers)
        {
            int sum = numbers.Sum();
            return sum;
        }
 }
public class CalculatorAdapter
 {
        personal 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 consumer 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 want to decide on the adapter design sample in our purposes when:

  • A category must be reused that doesn’t have an interface {that a} consumer requires.
  • Allow a system to make use of courses of one other system that’s incompatible with it.
  • Allow communication between a brand new and already present system that are unbiased of one another.

Source link