适配器模式

来源:互联网 发布:压缩过的js如何还原 编辑:程序博客网 时间:2024/05/29 16:40

出处:http://blog.csdn.net/a107494639/article/details/7567678

这里说两种适配器模式

1.类适配模式

在地球时代,所有坐骑都是只能跑,不能飞的,而现在很多坐骑在地球都可以飞了。假设,地球时代的坐骑只能跑,而现在的坐骑不仅能飞还能跑,我们可以用类适配模式来实现,要点是,适配器继承源类,实现目标接口:


[java] view plaincopy
  1. package adapter;  
  2.   
  3. /** 
  4.  * DOC 源 
  5.  *  
  6.  */  
  7. public class Sources {  
  8.   
  9.     public void run() {  
  10.         System.out.println("run");  
  11.     }  
  12.   
  13. }  

[java] view plaincopy
  1. package adapter;  
  2.   
  3. /** 
  4.  * DOC 目标接口 
  5.  *  
  6.  */  
  7. public interface ITarget {  
  8.   
  9.     public void run();  
  10.   
  11.     public void fly();  
  12. }  

[java] view plaincopy
  1. package adapter;  
  2.   
  3. /** 
  4.  * DOC 继承源类,实现目标接口,从而实现类到接口的适配 
  5.  *  
  6.  */  
  7. public class Adapter extends Sources implements ITarget {  
  8.   
  9.     @Override  
  10.     public void fly() {  
  11.         System.out.println("fly");  
  12.     }  
  13.   
  14. }  

2.对象适配模式

假设一个适配器要适配多个对象,可以将这些对象引入到适配器里,然后通过调用这些对象的方法即可:

[java] view plaincopy
  1. package adapter;  
  2.   
  3. /** 
  4.  *  
  5.  * DOC 源对象,只有跑的功能 
  6.  *  
  7.  */  
  8. public class Animal {  
  9.   
  10.     public void run() {  
  11.         System.out.println("run");  
  12.     }  
  13. }  

[java] view plaincopy
  1. package adapter;  
  2.   
  3. /** 
  4.  * DOC 目标接口,既能跑,又能飞 
  5.  *  
  6.  */  
  7. public interface ITarget {  
  8.   
  9.     public void run();  
  10.   
  11.     public void fly();  
  12. }  

[java] view plaincopy
  1. package adapter;  
  2.   
  3. /** 
  4.  * DOC 通过构造函数引入了源对象,并实现了目标的方法 
  5.  *  
  6.  */  
  7. public class Adapter implements ITarget {  
  8.   
  9.     private Animal animal;  
  10.   
  11.     // private animal animal2....可以适配多个对象  
  12.   
  13.     public Adapter(Animal animal) {  
  14.         this.animal = animal;  
  15.     }  
  16.   
  17.     /** 
  18.      * DOC 拓展接口要求的新方法 
  19.      */  
  20.     public void fly() {  
  21.         System.out.println("fly");  
  22.     }  
  23.   
  24.     /** 
  25.      * DOC 使用源对象的方法 
  26.      */  
  27.     public void run() {  
  28.         this.animal.run();  
  29.     }  
  30.   
  31. }  

原创粉丝点击