Adapter Pattern
It comes under structural type design pattern. It is used for making communication between two incompatible classes. It is used to provide a link between two incompatible classes.
The participants in this pattern are,
- Target
it defines domain specific interface which is used by client.
- Adaptee
It defines an existing interface that needs adapting; i.e., it is the class which contains the functionality, required by the client. However, its interface is not compatible with the client.
- Adapter
It is the class which implements target and inherits Adaptee class. It plays the role of communicator between Client and Adaptee.
- Client
It collaborates with objects conforming to the target interface; i.e., this class interacts with a class which implements the target interface. However, the communication class called Adaptee, is not compatible with the client.public class Client { - private ITarget target;
- public Client(ITarget target) {
- this.target = target;
- }
- public void MakeRequest() {
- target.Method_I();
- }
- }
- public interface ITarget {
- void Method_I();
- }
- public class Adapter: Adaptee, ITarget {
- public void Method_I() {
- Method_II();
- }
- }
- public class Adaptee {
- public void Method_II() {
- Console.WriteLine("Method_II() is called");
- }
- }
Example
The 'Client' class
- public class BillingSystem {
- private ITarget employeeSource;
- public BillingSystem(ITarget employeeSource) {
- this.employeeSource = employeeSource;
- }
- public void ShowEmployeeList() {
- List < string > employee = employeeSource.GetEmployeeList();
-
- Console.WriteLine("######### Employee List ##########");
- foreach(var item in employee) {
- Console.Write(item);
- }
- }
- }
The 'ITarget' interface
- public interface ITarget {
- List < string > GetEmployeeList();
- }
The 'Adaptee' class
- public class HRSystem {
- public string[][] GetEmployees() {
- string[][] employees = new string[4][];
- employees[0] = new string[] {
- "100",
- "Deepak",
- "Team Leader"
- };
- employees[1] = new string[] {
- "101",
- "Rohit",
- "Developer"
- };
- employees[2] = new string[] {
- "102",
- "Gautam",
- "Developer"
- };
- employees[3] = new string[] {
- "103",
- "Dev",
- "Tester"
- };
- return employees;
- }
- }
The 'Adapter' class
- public class EmployeeAdapter: HRSystem, ITarget {
- public List < string > GetEmployeeList() {
- List < string > employeeList = new List < string > ();
- string[][] employees = GetEmployees();
- foreach(string[] employee in employees) {
- employeeList.Add(employee[0]);
- employeeList.Add(",");
- employeeList.Add(employee[1]);
- employeeList.Add(",");
- employeeList.Add(employee[2]);
- employeeList.Add("\n");
- }
- return employeeList;
- }
- }
Adapter Design Pattern Demo
- class Program {
- static void Main(string[] args) {
- ITarget Itarget = new EmployeeAdapter();
- BillingSystem client = new BillingSystem(Itarget);
- client.ShowEmployeeList();
- Console.ReadLine();
- }
- }