Description
The adapter design pattern allows incompatible classes to interact with each other by converting the interface of one class into an interface expected by the clients, it works like a bridge between 2 incompatible interfaces
The adapter acts like a interpreter between classes. It inherits the target class interface, so it’s compatible with it, and by composition it uses the source class.
Assume that you have functionality written for an old car, that you receive from a third party and you cannot change it.
You also have written a library for the new Electronic Car. How to use the third party library? Well the Adapter does just that. It inherits the IECar and it converts commands to match the OldCar
The Old Library
public interface IOldCar { void FillWithGas(); void Accelerate(); void Break(); } public class OldCar : IOldCar { public void FillWithGas() { Console.WriteLine("Car is filling with gas"); } public void Accelerate() { Console.WriteLine("Car accelerating"); } public void Break() { Console.WriteLine("Car breaking"); } }
The ECar Library
public interface IElectricCar { void VoiceCommandToSlowDown(); void VoiceCommandToMoveForward(); void RechargeBatery(); } public class ElectricCar : IElectricCar { public void RechargeBatery() { Console.WriteLine("Ecar is recharching"); } public void VoiceCommandToMoveForward() { Console.WriteLine("ECar moving forward"); } public void VoiceCommandToSlowDown() { Console.WriteLine("ECar slowing down"); } }
The adapter
public class OldCarAdapter : IElectricCar { IOldCar oldCar; public OldCarAdapter(IOldCar oldCar) { this.oldCar = oldCar; } public void RechargeBatery() { oldCar.FillWithGas(); } public void VoiceCommandToMoveForward() { oldCar.Accelerate(); } public void VoiceCommandToSlowDown() { oldCar.Break(); } }
Now let’s see how we can use this adapter.
static void Main(string[] args) { IOldCar oldMercedes = new OldCar(); IElectricCar eMercedes = new ElectricCar(); IElectricCar oldMercedesAdapter = new OldCarAdapter(oldMercedes); List atackers = new List() { eMercedes, oldMercedesAdapter }; atackers.ForEach(x => x.VoiceCommandToSlowDown()); }