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

时间:2022-03-23 16:07:59

一、场景描述

“仪器数据采集器”包含采集数据以及发送数据给服务器两行为,则可定义“仪器数据采集器”接口,定义两方法“采集数据capture”和“发送数据senddata”。

“pdf文件数据采集器”实现时,要实现“仪器数据采集器”接口,实现“采集数据”方法;目前有“pdf文件内容解析工具”类pdffileextractor,该类实现pdf文件的数据解析;因此,可使“pdf文件数据采集器”继承“pdf文件内容解析工具”类,并实现“仪器数据采集器”接口,如下图所示:

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

适配器的作用是,继承现有的类,通过实现接口,扩展其用途。

类适配器继承源类,由于子类仅能继承一个父类,因此被继承的源类实现目标接口的方法多少也可以算做适配程度的高低。

二、示例代码

接口:

?
1
2
3
4
5
6
package lims.designpatterndemo.adapterclassdemo;
 
public interface equipmentdatacapture {
  public string capture(string filepath);
  public boolean senddata(string equipmentdata);
}

源类:

?
1
2
3
4
5
6
7
package lims.designpatterndemo.adapterclassdemo;
 
public class pdffileextractor {
  public string capture(string filepath){
    return "pdf file content";
  }
}

适配器类:

?
1
2
3
4
5
6
7
8
9
10
package lims.designpatterndemo.adapterclassdemo;
 
public class pdffilecapture extends pdffileextractor implements equipmentdatacapture {
 
  @override
  public boolean senddata(string equipmentdata) {
    return false;
  }
 
}

调用示例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
package lims.designpatterndemo.adapterclassdemo;
 
public class classadapterdemo {
 
  public static void main(string[] args) {
    pdffilecapture capture = new pdffilecapture();
    string filecontent = capture.capture("");
    system.out.println(filecontent);
    boolean rst = capture.senddata(filecontent);
    system.out.println(rst);
  }
 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/mahongbiao/p/8626610.html