Adaptor Design Pattern

Definition
 
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
 
Note: 
  1. Wrap an existing class with a new interface.
  2. Impedance match an old component to a new system
  3. Adapter, the modifier, is about creating an intermediary abstraction that translates, or maps to the old component to the new system. Clients call methods on the Adapter object which redirects them into calls to the legacy component. This strategy can be implemented either with inheritance or with aggregation.
  4. Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an improved interface.
Design
 
Please refer to the code
 
Some of best example: Adaptor for Two pin plug, We can have only one adaptor
 
UML Diagram
 
From GoF
 
1.gif
 
2.gif
 
Code
  1. /// <summary>  
  2. /// Target Wraper base  
  3. /// </summary>  
  4. public class AdaptorTarget  
  5. {  
  6.     public virtual void Request()  
  7.     {  
  8.         Console.WriteLine("Called Target Request()");  
  9.     }  
  10. }  
  11.   
  12. /// <summary>  
  13. /// Adapter -- Wrapper  
  14. /// </summary>  
  15. public class Adaptor : AdaptorTarget  
  16. {  
  17.     internal OldSystem.Adaptee Adaptee  
  18.     {  
  19.         get { return new OldSystem.Adaptee();}  
  20.         set { ;}  
  21.     }  
  22.     public override void Request()  
  23.     {  
  24.         Adaptee.OldMethod();  
  25.     }  
  26. }  
  27.   
  28. namespace OldSystem  
  29. {  
  30.     /// <summary>  
  31.     /// Adaptee -- Old system  
  32.     /// </summary>  
  33.     internal class Adaptee  
  34.     {  
  35.         internal void OldMethod()  
  36.         {  
  37.             Console.WriteLine("Called incompatable system method....");  
  38.         }  
  39.     }  

Client
  1. internal static AdaptorTarget AdaptorTargetLocal  
  2. {  
  3.     get  
  4.     {  
  5.         return new Adaptor();  
  6.     }  
  7.     set  
  8.     {  
  9.     }  
  10. }  
  11. static void Main(string[] args)  
  12. {  
  13.     AdaptorTargetLocal.Request();  

Note: Adator provides wrapper for each system. Where are Façade does differently. And Proxy is also a wrapper but it exposes the same interfaces as the subsystem.
 
Hope this helps.


Similar Articles