Skip to main content

Adapter Design Pattern - C#

Adapter pattern falls under Structural Pattern of Gang of Four (GOF) Design Patterns in .Net. The Adapter pattern allows a system to use classes of another system that is incompatible with it. It is especially used for toolkits and libraries. In this article, I would like share what is adapter pattern and how is it work?


What is Adapter Pattern

Adapter pattern acts as a bridge between two incompatible interfaces. This pattern involves a single class called adapter which is responsible for communication between two independent or incompatible interfaces.
For Example: A card reader acts as an adapter between memory card and a laptop. You plugins the memory card into card reader and card reader into the laptop so that memory card can be read via laptop.

Adapter Pattern - UML Diagram & Implementation

The UML class diagram for the implementation of the Adapter design pattern is given below:
The classes, interfaces and objects in the above UML class diagram are as follows:
  1. ITarget

    This is an interface which is used by the client to achieve its functionality/request.
  2. Adapter

    This is a class which implements the ITarget interface and inherits the Adaptee class. It is responsible for communication between Client and Adaptee.
  3. Adaptee

    This is a class which have the functionality, required by the client. However, its interface is not compatible with the client.
  4. Client

    This is a class which interact with a type that implements the ITarget interface. However, the communication class called adaptee, is not compatible with the client

C# - Implementation Code

  1. public class Client
  2. {
  3. private ITarget target;
  4.  
  5. public Client(ITarget target)
  6. {
  7. this.target = target;
  8. }
  9.  
  10. public void MakeRequest()
  11. {
  12. target.MethodA();
  13. }
  14. }
  15.  
  16. public interface ITarget
  17. {
  18. void MethodA();
  19. }
  20.  
  21. public class Adapter : Adaptee, ITarget
  22. {
  23. public void MethodA()
  24. {
  25. MethodB();
  26. }
  27. }
  28.  
  29. public class Adaptee
  30. {
  31. public void MethodB()
  32. {
  33. Console.WriteLine("MethodB() is called");
  34. }
  35. }

Adapter Pattern - Example

Who is what?

The classes, interfaces and objects in the above class diagram can be identified as follows:
  1. ITraget - Target interface
  2. Employee Adapter- Adapter Class
  3. HR System- Adaptee Class
  4. ThirdPartyBillingSystem - Client

C# - Sample Code

  1. /// <summary>
  2. /// The 'Client' class
  3. /// </summary>
  4. public class ThirdPartyBillingSystem
  5. {
  6. private ITarget employeeSource;
  7. public ThirdPartyBillingSystem(ITarget employeeSource)
  8. {
  9. this.employeeSource = employeeSource;
  10. }
  11. public void ShowEmployeeList()
  12. {
  13. List<string> employee = employeeSource.GetEmployeeList();
  14. //To DO: Implement you business logic
  15. Console.WriteLine("######### Employee List ##########");
  16. foreach (var item in employee)
  17. {
  18. Console.Write(item);
  19. }
  20. }
  21. }
  22.  
  23. /// <summary>
  24. /// The 'ITarget' interface
  25. /// </summary>
  26. public interface ITarget
  27. {
  28. List<string> GetEmployeeList();
  29. }
  30.  
  31. /// <summary>
  32. /// The 'Adaptee' class
  33. /// </summary>
  34. public class HRSystem
  35. {
  36. public string[][] GetEmployees()
  37. {
  38. string[][] employees = new string[4][];
  39. employees[0] = new string[] { "100", "Deepak", "Team Leader" };
  40. employees[1] = new string[] { "101", "Rohit", "Developer" };
  41. employees[2] = new string[] { "102", "Gautam", "Developer" };
  42. employees[3] = new string[] { "103", "Dev", "Tester" };
  43. return employees;
  44. }
  45. }
  46.  
  47. /// <summary>
  48. /// The 'Adapter' class
  49. /// </summary>
  50. public class EmployeeAdapter : HRSystem, ITarget
  51. {
  52. public List<string> GetEmployeeList()
  53. {
  54. List<string> employeeList = new List<string>();
  55. string[][] employees = GetEmployees();
  56. foreach (string[] employee in employees)
  57. {
  58. employeeList.Add(employee[0]);
  59. employeeList.Add(",");
  60. employeeList.Add(employee[1]);
  61. employeeList.Add(",");
  62. employeeList.Add(employee[2]);
  63. employeeList.Add("\n");
  64. }
  65. return employeeList;
  66. }
  67. }
  68.  
  69. ///
  70. /// Adapter Design Pattern Demo
  71. ///
  72. class Program
  73. {
  74. static void Main(string[] args)
  75. {
  76. ITarget Itarget = new EmployeeAdapter();
  77. ThirdPartyBillingSystem client = new ThirdPartyBillingSystem(Itarget);
  78. client.ShowEmployeeList();
  79. Console.ReadKey();
  80. }
  81. }

Adapter Pattern Demo - Output

When to use it?

  1. Allow a system to use classes of another system that is incompatible with it.
  2. Allow communication between new and already existing system which are independent to each other
  3. Ado.Net SqlAdapter, OracleAdapter, MySqlAdapter are best example of Adapter Pattern.

Note

  1. Internally, Adapter use Factory design pattern for creating objects. But it can also use Builder design pattern and prototype design pattern for creating product. It completely depends upon your implementation for creating products.
  2. Adapter can be used as an alternative to Facade to hide platform-specific classes.
  3. When Adapter, Builder, and Prototype define a factory for creating the products, we should consider the following points :
    1. Adapter use the factory for creating objects of several classes.
    2. Builder use the factory for creating a complex product by using simple objects and a step by step approach.
    3. Prototype use the factory for building a product by copying an existing product.

Comments

Popular posts from this blog

Accessing File Stored in Windows Azure Blob Storage Using jQuery

Did you know it was possible to access the Windows Azure Blob Storage directly from JavaScript, for example using jQuery? At first, it sounds obvious, since Blobs are after all accessible from a public UR. But in practice, there is a very big hurdle: the Web browser’s Same Origine Policy or SOP, that restricts JavaScript code to accessing resources originating from the same site the script was loaded from. This means that you will never be able to load a Windows Azure Blob using XMLHttpRequest for example! Fortunately, there is a popular workaround called JSONP (“JSON with Padding”). The idea behind this technique is that the script tag is not submitted to the SOP: an HTML page can thus load a JavaScript file from any site. So, if you expose your data in an “executable” form in JavaScript, a page will be able to load this data using a script tag. For example: <script type=”text/javascript” src=”http://www.sandeepknarware.in/exemple.jsonp”> </script> But how can ...

Support for debugging lambda expressions with Visual Studio 2015

Anyone who uses LINQ (or lambdas in general) and the debugger will quickly discover the dreaded message “Expression cannot contain lambda expressions”. Lack of lambda support has been a limitation of the Visual Studio Debugger ever since Lambdas were added to C# and Visual Basic.  With visual studio 2015 Microsoft has added support for debugging lambda expressions. Let’s first look at an example, and then I’ll walk you through current limitations. Example To try this yourself, create a new C# Console app with this code: using System.Diagnostics; using System.Linq; class Program { static void Main() { float[] values = Enumerable.Range(0, 100).Select(i => (float)i / 10).ToArray(); Debugger.Break(); } } Then compile, start debugging, and add “values.Where(v => (int)v == 3).ToArray()” in the Watch window. You’ll be happy to see the same as what the screenshot above shows you. I am using Visual Studio 2015 Preview and it has some limitati...

gcAllowVeryLargeObjects Element

There are numerous new features coming with .NET 4.5 and here, on this blog, you can find several posts about it. But the feature we are goint to talk about today is very exciting, because we were waiting for it more than 10 years. Since .NET 1.0 the memory limit of .NET object is 2GB. This means you cannot for example create array which contains elements with more than 2GB in total. If try to create such array, you will get the OutOfMemoryException. Let’s see an example how to produce OutOfMemoryException. Before that Open Visual Studio 2012, and create C# Console Application, like picture below. First lets create simple struct with two double members like example below: 1 2 3 4 5 6 7 8 9 10 11 12 public struct ComplexNumber {      public double Re;      public double Im;      public ComplexNumber( double re, double im)      {    ...