Adapter (适配器模式)

适配器模式:

将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

有两种适配器模式:

1)类适配器 (通过继承的方式)

2)对象适配器 (采取对象组合的模式)

-------------------------- 类适配器 -----------------------------

Target.java

[java] view plain copy
  1. package com.adapter ;  
  2.   
  3. public interface Target  
  4. {  
  5.     public void method() ;  
  6.   
  7. }  

被适配器类

Adaptee.java

[java] view plain copy
  1. package com.adapter ;  
  2.   
  3. public class Adaptee  
  4. {  
  5.     public void method2()  
  6.     {  
  7.         System.out.println("Adapter-->method2()") ;  
  8.     }  
  9. }  

适配器类 Adapter.java

[java] view plain copy
  1. package com.adapter ;  
  2.   
  3. public class Adapter extends Adaptee implements Target  
  4. {  
  5.     public void method()  
  6.     {  
  7.         super.method2() ;//或者this.method2() ;  
  8.     }  
  9. }  

Client.java

[java] view plain copy
  1. package com.adapter ;  
  2.   
  3. public class Client  
  4. {  
  5.     public static void main(String[] args)  
  6.     {  
  7.         Target t = new Adapter() ;  
  8.         t.method() ;  
  9.     }  
  10. }  

-------------------------- 对象适配器 -----------------------------

Target.java

[java] view plain copy
  1. package com.adapter ;  
  2.   
  3. public interface Target  
  4. {  
  5.     public void method() ;  
  6.   
  7. }  

被适配器类

Adaptee.java

[java] view plain copy
  1. package com.adapter ;  
  2.   
  3. public class Adaptee  
  4. {  
  5.     public void method2()  
  6.     {  
  7.         System.out.println("Adapter-->method2()") ;  
  8.     }  
  9. }  

适配器类 Adapter.java

[java] view plain copy
  1. package com.adapter ;  
  2.   
  3. public class Adapter implements Target  
  4. {  
  5.     private Adaptee adaptee;  
  6.       
  7.     public Adapter(Adaptee adaptee)  
  8.     {  
  9.         this.adaptee = adaptee ;  
  10.     }  
  11.   
  12.     public void method()  
  13.     {  
  14.         this.adaptee.method2() ;  
  15.     }  
  16. }  

Client.java

[java] view plain copy
  1. package com.adapter ;  
  2.   
  3. public class Client  
  4. {  
  5.     public static void main(String[] args)  
  6.     {  
  7.         Adaptee adaptee = new Adaptee() ;  
  8.         Target t = new Adapter(adaptee) ;  
  9.         t.method() ;  
  10.     }  
  11. }  
原文地址:https://www.cnblogs.com/hoobey/p/5294392.html