adapter-pattern
IT Management

Adapter Pattern – Cybarlab


Adapter style pattern enables incompatible classes to interact by transforming the user interface of one class into another. It resembles a translator. When 2 heads of nations who do not speak a typical language fulfill, normally an interpreter sits in between them and equates the discussion, hence making it possible for interaction.

Let’s believe, we have 2 classes. One take variety input, another one offer a list as output. Now if we wish to interact then we require an adapter.

 public class Calculator
{
public int GetSum( int[] numbers).
{
int amount = numbers.Sum();.
return amount;.
}
} 
 public class CalculatorAdapter.
{
personal readonly Calculator _ calculator;.
public CalculatorAdapter().
{
_ calculator =brand-new Calculator();.
}

public int GetTotalSum( List numbers).
{
int amount = _ calculator.GetSum( numbers.ToArray());.
return amount;.
}
} 

Here CalculatorAdapter class is an adapter. Our matching customer code is:

 class Program.
{
fixed space Main( string[] args).
{
CalculatorAdapter calculator = brand-new CalculatorAdapter();.
List numbers = brand-new List {1, 2, 3, 4, 5};.
var amount = calculator.GetTotalSum( numbers);.
Console.WriteLine( amount);.
}
} 

We require to pick the adapter style pattern in our applications when:

  • A class requires to be recycled that does not have a user interface that a customer needs.
  • Permit a system to utilize classes of another system that is incompatible with it.
  • Permit interaction in between a brand-new and currently existing system which are independent of each other.

Source link