索引
将一个类的接口转换成客户希望的另外一个接口。
Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
Convert the interface of a class into another interface clients expect.
Adapter lets classes work together that couldn‘t otherwise because of incompatible interfaces.
类适配器使用多重继承对一个接口与另一个接口进行匹配。
对象适配器依赖于对象组合。
Target
Client
Adaptee
Adapter
在以下情况下可以使用 Adapter 模式:
1 namespace AdapterPattern.Implementation1 2 { 3 public class ParentAdaptee 4 { 5 public virtual string SpecificRequest() 6 { 7 return "ParentAdaptee"; 8 } 9 } 10 11 public class ChildAdaptee : ParentAdaptee 12 { 13 public override string SpecificRequest() 14 { 15 return "ChildAdaptee"; 16 } 17 } 18 19 public class Target 20 { 21 public virtual string Request() 22 { 23 return "Target"; 24 } 25 } 26 27 public class Adapter : Target 28 { 29 private ParentAdaptee _adaptee; 30 31 public Adapter(ParentAdaptee adaptee) 32 { 33 _adaptee = adaptee; 34 } 35 36 public override string Request() 37 { 38 return _adaptee.SpecificRequest(); 39 } 40 } 41 42 public class Client 43 { 44 public void TestCase1() 45 { 46 ParentAdaptee adaptee = new ChildAdaptee(); 47 Target target = new Adapter(adaptee); 48 var result = target.Request(); 49 } 50 } 51 }
1 namespace AdapterPattern.Implementation2 2 { 3 public class ParentAdaptee 4 { 5 public virtual string SpecificRequest() 6 { 7 return "ParentAdaptee"; 8 } 9 } 10 11 public class ChildAdaptee : ParentAdaptee 12 { 13 public override string SpecificRequest() 14 { 15 return "ChildAdaptee"; 16 } 17 } 18 19 public interface ITarget 20 { 21 string Request(); 22 } 23 24 public class Adapter : ChildAdaptee, ITarget 25 { 26 public Adapter() 27 { 28 } 29 30 public string Request() 31 { 32 return base.SpecificRequest(); 33 } 34 } 35 36 public class Client 37 { 38 public void TestCase2() 39 { 40 ITarget target = new Adapter(); 41 var result = target.Request(); 42 } 43 } 44 }
设计模式之美:Adapter(适配器),布布扣,bubuko.com
原文:http://www.cnblogs.com/gaochundong/p/design_pattern_adapter.html