Before starting, I would request that you visit the previous articles on Design Patterns series:
I am here to continue the discussion around Design Patterns. Today we will go through one of the structural design patterns called Adapter. Before talking about its implementation let’s begin with defining it.
As per GOF guys, Adapter pattern is defined as the following.
“Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.”
Well! Let’s understand what they mean.
It means that Adapter pattern links two incompatible interfaces which have the same functionality but their methods are called a little differently. Sometimes it is also called a wrapper.
How Adapter pattern works
Adapter pattern can be used to integrate with other external components that might have the same functionality we need but their functions are not called quite the same way. Assume we have an Employee class with a function defined as PrintEmployee and we work with an external contract employee provider that has an EmployeeDetail class with a function as ListEmployee.
Here we can create an adapter class to wrap the external EmployeeDetailclass so that a call to PrintEmployee() of the adapter is delegated to ListEmployee() of the external class.
Let’s understand this by a simple example.
-
-
-
- public class EmployeeDetail
- {
-
- public static void ListEmployee(List < string > empList)
- {
- foreach(stringempinempList)
- {
- Console.WriteLine("Employee Name: " + emp);
- }
- }
- }
-
-
-
-
- public interface IEmployee
- {
- voidPrintEmployee(List < string > empList);
- }
-
-
-
-
- public class EmployeeAdapter: IEmployee
- {
- public void PrintEmployee(List < string > empList)
- {
- EmployeeDetail.ListEmployee(empList);
- }
- }
As you can see in the above we have defined Adapter (EmployeeAdapter), Target Interface (IEmployee), Adapter (EmployeeDetail). Now let’s define client to see the action end to end.
- staticvoid Main()
- {
- Console.Title = "Adapter pattern demo";
-
-
- List < string > empList = newList < string > ();
- empList.Add("Prakash");
- empList.Add("Amit");
- empList.Add("Pankaj");
- IEmployeeemp = newEmployeeAdapter();
- emp.PrintEmployee(empList);
- }
Output:
Here we can see that with the help of EmployeeAdapter class, client is able to print the employee records.
So in summary, adapter pattern can be used when the current system needs to use functions of another system that is incompatible with it. Some of the most popular examples can be SqlAdapter, OracleAdapter, MySqlAdapter in ADO.NET.
Hope you have liked the article. I look forward for your comments/suggestions.
Read more articles on Design Patterns: