Java设计模式之:适配器模式 - Go语言中文社区

Java设计模式之:适配器模式


这里说两种适配器模式

1、类适配模式

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

  1. package adapter;  
  2.  
  3. /**  
  4.  * DOC 源  
  5.  *   
  6.  */ 
  7. public class Sources {  
  8.     public void run() {  
  9.         System.out.println("run");  
  10.     }  
  1. package adapter;  
  2.  
  3. /**  
  4.  * DOC 目标接口  
  5.  *   
  6.  */ 
  7. public interface ITarget {  
  8.     public void run();  
  9.     public void fly();  
  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.     }  

2、对象适配模式

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

  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.     }  
  1. package adapter;  
  2.  
  3. /**  
  4.  * DOC 目标接口,既能跑,又能飞  
  5.  *   
  6.  */ 
  7. public interface ITarget {  
  8.     public void run();  
  9.     public void fly();  
  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.     }  

原文链接:http://blog.csdn.net/a107494639/article/details/7567678

版权声明:本文来源51CTO,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:http://developer.51cto.com/art/201205/336608.htm
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-05-16 01:25:59
  • 阅读 ( 1175 )
  • 分类:设计模式

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢