Adapter pattern is a structural design pattern which is used for making two interfaces compatible which otherwise were incompatible. It is commonly referred to as wrapper pattern. This can be best explained by considering a simple 1-1 adapter. Below is an adapter which has provision for two wire input and converts it to a 3-output one.
Adapter pattern works exactly the same way. So, you have one thing that has a particular interface (In this case two input wire) or a contract and you need to convert it to a 3-input one and our output contract is accepting a 3-input one. This is achieved by sticking an adapter in between these two interfaces. The Adapter pattern converts the interface of a class into another interface that clients accept. Adapter lets classes work together which couldn’t otherwise because of incompatible interfaces.
UML DiagramConsider the below UML diagram where the Client class has a type of ITarget interface and using this interface wants to execute SpecificRequest method of Adaptee class which is of type IAdaptee which has a different contract from ITarget. This is achieved by having an adapter class between these two interfaces. The Adapter class inherits from ITarget and has a reference to IAdaptee. So, the Client class can now invoke method Request of Adapter class which delegates to SpecificRequest method of Adaptee class.
CodeBelow is a C# implementation of the UML diagram. The client class uses concrete implementation of ITarget to call request method of Adapter class. The Adapter class has a reference to IAdaptee injected by constructor. Using this reference Specific Request method of Adaptee class is invoked which performes the desired action.
Adapter pattern very useful in scenarios where we use external libraries which have a different contract than the client request, Adaptee in this case is external library. We have an adapter in between the library so in future if we decided to change to an different library we can just change the adapter to use the new library. The Adapter pattern shouldn’t change the underlying behavior. The intention is blindly to pass on the request to make the incompatible interfaces work together.
GitHub Link: Adapter Pattern
#7DayOf100DaysOfCode
Comments