Adapter Design Pattern in the real world

Amr elshaer
3 min readMay 15, 2021

--

One of the important design patterns is the adapter design pattern, let’s say you have new mobile and the old charger is not compatible with the new mobile you have two options to buy a new charger or buy an adapter that reuses the old charger, so we buy an adapter instead of buy a new charger because the charger is more expensive. so this behavior that adapter design pattern use is to reuse existing code instead of adding new implementation.

let’s go in-depth and show examples.

I have adaptee EmployeeManager class that get employees in xml like this

what task orders for me to get employees in JSON so instead of adding new implementation we will reuse employee-manager

we will add a target folder and add an employee interface like this:

second, we will add an Adapter folder and add EmployeeAdapter class that implements EmployeeManager and employee interface

the last client will use EmployeeAdapter to get an employee in JSON

Another real-world example is logging in dotnet, logging in dotnet is not more effective for memory let’s our example

We create loggerFactory whose default logging level is Information in this case when we log information like in our example logging user age it will convert the Age (int) to an object and convert a value type to reference type this will add heavy on GC, but this is normally way if the default log level is information and I log info but what I make the default log level is warning and this will not show the info message but will convert Age to object and add a lot of data I don’t need it, and be attention the implementation of LogInformation of dotnet.

so what I need to make is to make another generic method when I log to accept the type of arg instead of an object and also check the log level is enabled before passing arg to LogInformation. the adapter pattern will help to add new logic on top of the implementation of dotnet.

so we will update our to use our logging adapter instead of

this will improve our performance and not convert our value type to a reference type (boxing) in the case we don’t need to convert when the log level is not enabled.

source code GitHub.

--

--

Amr elshaer
Amr elshaer

Written by Amr elshaer

Software engineer | .Net ,C# ,Angular, Javascript

No responses yet