适配器模式

来源:互联网 发布:微点主动防御软件 编辑:程序博客网 时间:2024/06/10 00:36
仔细看

根据下面的图片和代码进行的自我总结:


适配器模式:就好像是一个两项的插头要去插三项的插座,这是不能直接插进去的,我们只能将中间放一个适配器,这样将两项的插头插到适配器中,在用适配器和三项插头相连接,就会将原来不能连接的内容进行连接,主要的实现就是适配器继承三项的插座,实现两项的这个标准的插头接口,而在实现两项的标准接口中的抽象方法时,用super点来调用继承的这个三项插座这个父类中的方法,从而将他们进行连接

  1. // 已存在的、具有特殊功能、但不符合我们既有的标准接口的类  
  2. class Adaptee {  
  3.     public void specificRequest() {  
  4.         System.out.println("被适配类具有 特殊功能...");  
  5.     }  
  6. }  
  7.   
  8. // 目标接口,或称为标准接口  
  9. interface Target {  
  10.     public void request();  
  11. }  
  12.   
  13. // 具体目标类,只提供普通功能  
  14. class ConcreteTarget implements Target {  
  15.     public void request() {  
  16.         System.out.println("普通类 具有 普通功能...");  
  17.     }  
  18. }  
  19.    
  20. // 适配器类,继承了被适配类,同时实现标准接口  
  21. class Adapter extends Adaptee implements Target{  
  22.     public void request() {  
  23.         super.specificRequest();  
  24.     }  
  25. }  
  26.    
  27. // 测试类public class Client {  
  28.     public static void main(String[] args) {  
  29.         // 使用普通功能类  
  30.         Target concreteTarget = new ConcreteTarget();  
  31.         concreteTarget.request();  
  32.           
  33.         // 使用特殊功能类,即适配类  
  34.         Target adapter = new Adapter();  
  35.         adapter.request();  
  36.     }  


0 0