适配器模式

来源:互联网 发布:mac的onedrive在哪里 编辑:程序博客网 时间:2024/06/05 21:00

适配器模式

定义:将一个类转换成客户希望看到的另一个接口,使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。简单来说:你现在有一个A的对象,但是现在需要B接口的对象,通过适配器模式可将A伪装成一个B的对象,达到目的,A的对象、B接口在功能上要类似。核心便是转化二字。

角色:目标接口,适配器,被适配接口

分类:有对象适配器和类适配器两种。类适配器是采用多重继承的方式,使适配器同事继承目标接口和被适配接口。

对象适配器则是适配器实现目标接口,同时拥有一个被适配接口的对象,当client需要调用目标接口方法时,则通过调用被适配接口的对象来完成任务。

示例代码:

[java] view plaincopy
  1. /** 
  2.  * 目标接口 
  3.  * @author sky 
  4.  * 
  5.  */  
  6. public interface GoodStudent {  
  7.       
  8.     public void hardWorking();  
  9.   
  10. }  
  11.   
  12. /** 
  13.  * 被适配者接口 
  14.  * @author sky 
  15.  * 
  16.  */  
  17. public interface BadStudent {  
  18.   
  19.     public void lazyWorking();  
  20. }  
  21.   
  22. /** 
  23.  * 被适配子类 
  24.  * @author sky 
  25.  * 
  26.  */  
  27. public class Jon implements BadStudent {  
  28.   
  29.     @Override  
  30.     public void lazyWorking() {  
  31.         System.out.println("学习一分钟");  
  32.   
  33.     }  
  34.   
  35. }  
  36.   
  37. /** 
  38.  * 适配器类,将一个坏学生,包装成好学生 
  39.  * @author sky 
  40.  * 
  41.  */  
  42. public class Adapter implements GoodStudent {  
  43.   
  44.     private BadStudent badStudent;  
  45.       
  46.     public Adapter(BadStudent bStudent){  
  47.         badStudent = bStudent;  
  48.     }  
  49.       
  50.     @Override  
  51.     public void hardWorking() {  
  52.         for (int i = 0; i < 10; i++) {   //坏学生要付出10倍的努力  
  53.             badStudent.lazyWorking();  
  54.         }  
  55.     }  
  56.   
  57. }  
  58.   
  59. /** 
  60.  * 测试类 
  61.  * @author sky 
  62.  * 
  63.  */  
  64. public class Test {  
  65.       
  66.     private GoodStudent goodStudent;  
  67.       
  68.     public Test(GoodStudent gStudent){  
  69.         goodStudent = gStudent;  
  70.     }  
  71.       
  72.     public void testWork(){  
  73.         goodStudent.hardWorking();  
  74.     }  
  75.       
  76.     public static void main(String[] args) {  
  77.         BadStudent badStudent = new Jon();  
  78.         Adapter adapter = new Adapter(badStudent);  
  79.         Test test = new Test(adapter);  
  80.         test.testWork();  
  81.     }  
  82. }  
0 0
原创粉丝点击