Code Example |
1 // Adapter 2 3 // Intent: "Convert the interface of a class into another interface 4 // clients expect. Adapter lets classes work together that couldn't 5 // otherwise because of incompatible interfaces". 6 7 // For further information, read "Design Patterns", p139, Gamma et al., 8 // Addison-Wesley, ISBN:0-201-63361-2 9 10 /**//* Notes: 11 * Adapters are often used when client code is written to expect classes 12 * from one framework, and it meant to work with classes from a totally 13 * different framework. Assume you cannot change the code of either framework. 14 * the solution is for you to write an adapter, which appears like a 15 * native class to each framework. 16 * 17 * There are two different types of adapters - class adapter and object 18 * adapter. Class adapters are based on multiple inheritance - specifically 19 * the interface of the target class and the implementation of the adaptee. 20 * Unfortunately C# supports multiple inheritance for interfaces but not 21 * for classes. Object adapters derive from the target (single inheritance) 22 * and maintain a private instance of the adoptee. 23 * 24 * The sample code here shows an object adapter. We have a class called 25 * FrameworkYAdaptee which we wish to use, yet the (bulk of) the client code 26 * (in GenericClientCode) is written to expect a class called FrameworkXTarget. 27 * To solve the probelm we create an Adapter class, which it a FrameworkXTarget 28 * to the client, and calls FrameworkYAdaptee. 29 * 30 */ 31 32 namespace Adapter_DesignPattern 33  { 34 using System; 35 36 class FrameworkXTarget 37 { 38 virtual public void SomeRequest(int x) 39 { 40 // normal implementation of SomeRequest goes here 41 } 42 } 43 44 class FrameworkYAdaptee 45 { 46 public void QuiteADifferentRequest(string str) 47 { 48 Console.WriteLine("QuiteADifferentRequest = {0}", str); 49 } 50 } 51 52 class OurAdapter : FrameworkXTarget 53 { 54 private FrameworkYAdaptee adaptee = new FrameworkYAdaptee(); 55 override public void SomeRequest(int a) 56 { 57 string b; 58 b = a.ToString(); 59 adaptee.QuiteADifferentRequest(b); 60 } 61 } 62 63 /**//// <summary> 64 /// Summary description for Client. 65 /// </summary> 66 public class Client 67 { 68 void GenericClientCode(FrameworkXTarget x) 69 { 70 // We assume this function contains client-side code that only 71 // knows about FrameworkXTarget. 72 x.SomeRequest(4); 73 // other calls to FrameworkX go here 74 //  75 } 76 77 public static int Main(string[] args) 78 { 79 Client c = new Client(); 80 FrameworkXTarget x = new OurAdapter(); 81 c.GenericClientCode(x); 82 return 0; 83 } 84 } 85 } 86 87 |