- Creating Web Components in Angular - February 23, 2021
- What is your Communication Style? - August 1, 2020
- Sharing is caring? - January 28, 2020
Adapter design pattern is usually used when we want to use a method from a third party tool, but the method takes an interface A as an input. We want the method to work with our interface B. So to use that method, we convert our interface B to the required interface (interface A) using an adapter class. An example will make this more clear.
Now we have a class PrintHumanName which has a method Print that we want to use. Now this method print uses IHuman interface as an input parameter.
This method can be used, if the input parameter is a class that implements IHuman interface as below:
But we want to use a class that implements IAnimal interface as an input parameter. So, we write the code as below, but this does not work.
So to be able to use a class that implements IAnimal interface, we create an adapter class as below:
Now we can use a class implementing IAnimal interface as the input.
This will give the output as below:
The whole code can be viewed as below:
namespace AdapterDesignPattern
{
class Program
{
static void Main(string[] args)
{
//Human john = new Human("Smith", "John");
//PrintHumanName.Print(john);
Animal tommy = new Animal("Tommy");
//PrintHumanName.Print(tommy);
PrintHumanName.Print(new AnimalToHumanAdapter(tommy));
}
}
static class PrintHumanName
{
public static void Print(IHuman human)
{
Console.WriteLine(human.FName + '-' + human.LName);
}
}
public interface IHuman
{
//string Name { get; set; }
string FName { get; set; }
string LName { get; set; }
}
public class Human : IHuman
{
public Human(string Lname, string Fname)
{
LName = Lname;
FName = Fname;
}
public string FName { get; set; }
public string LName { get; set; }
}
public interface IAnimal
{
string AnimalName { get; set; }
}
public class Animal : IAnimal
{
public string AnimalName { get; set; }
public Animal(string aName)
{
AnimalName = aName;
}
}
public class AnimalToHumanAdapter : IHuman
{
private readonly IAnimal animal;
public AnimalToHumanAdapter(IAnimal animal)
{
this.animal = animal;
}
public string FName {
get { return animal.AnimalName; }
set { animal.AnimalName = value; }
}
public string LName {
get { return "No last name"; }
set { animal.AnimalName = "No last name"; }
}
}
}
You can also download it from here.