Introduction
An adapter design pattern is used between incompatible interfaces. It converts the incompatible interface into a compatible interface that can be used by the client. So we can say that an adapter design pattern is used to allow two incompatible interfaces to communicate. The adapter plays the role of converter or translator.
The adapter is most commonly known as Wrappers because it wraps the adapter with a new interface that can be used by the client.
To handle the incompatibility, we use different approaches, and based on that, we can classify the Adapter Pattern into 2 parts.
- Object Adapter Pattern
- Class Adapter Pattern
Object Adapter Design Pattern
In Object Adapter Pattern, Incompatibility is handled by creating the object.
Class Adapter Design Pattern
Class Adapter Design Pattern Incompatibility is handled by inheritance.
Some Real-world Examples
The following image is my personal use of LED Monitor. I use my monitor in different ways, which you can see in the following image.
Let me explain the UML Diagram of the Adapter pattern using a real example of programming. I have an interface that returns a list of Lumia Mobiles in JSON, but the Client is expecting the list of Lumia Mobile features in XML format. Let‘s solve it using the Adapter patter.
LumiaJSONAdaptee.CS
public class LumiaJSONAdaptee
{
public string GetLumiaMobilesJSONSpecifications()
{
List<LumiaMobile> LumiaMobiles = new List<LumiaMobile>();
LumiaMobiles.Add(new LumiaMobile
{
ModelId = "lumia550",
Height = "136.1 mm",
Width = "67.8 mm",
Thickness = "9.9 mm",
Weight = "141.9 g"
});
LumiaMobiles.Add(new LumiaMobile
{
ModelId = "lumia950",
Height = "145 mm",
Width = "73.2 mm",
Thickness = "8.2 mm",
Weight = "150 g"
});
LumiaMobiles.Add(new LumiaMobile
{
ModelId = "Text",
Height = "",
Width = "",
Thickness = "8.2 mm",
Weight = "150 g"
});
dynamic collectionLumiaMobiles = new
{
lumiaMobiles = LumiaMobiles
};
return JsonConvert.SerializeObject(collectionLumiaMobiles);
}
}
LumiaMobile.cs
public class LumiaMobile
{
public string ModelId { get; set; }
public string Height { get; set; }
public string Width { get; set; }
public string Thickness { get; set; }
public string Weight { get; set; }
}
ILumiaXMLTarget.cs
interface ILumiaXMLTarget
{
XmlDocument GetLumiaMobilesXMLSpecifications();
}
LumiaXMLAdapter.cs
class LumiaXMLAdapter : ILumiaXMLTarget
{
public XmlDocument GetLumiaMobilesXMLSpecifications()
{
LumiaJSONAdaptee lumiaJsonAdaptee = new LumiaJSONAdaptee();
string jsonLumia = lumiaJsonAdaptee.GetLumiaMobilesJSONSpecifications();
XmlDocument doc = JsonConvert.DeserializeXmlNode(jsonLumia, "MicrosoftLumiaMobiles", true);
return doc;
}
}
class MyLumiaClient
{
private ILumiaXMLTarget _lumiaXmlTarget;
public MyLumiaClient(ILumiaXMLTarget lumiaXmlTarget)
{
_lumiaXmlTarget = lumiaXmlTarget;
}
public XmlDocument GetLumiaData()
{
return _lumiaXmlTarget.GetLumiaMobilesXMLSpecifications();
}
}