一、場景描述
“儀器數據采集器”包含采集數據以及發送數據給服務器兩行為,則可定義“儀器數據采集器”接口,定義兩方法“采集數據capture”和“發送數據senddata”。
“pdf文件數據采集器”實現時,要實現“儀器數據采集器”接口,實現“采集數據”方法;目前有“pdf文件內容解析工具”類pdffileextractor,該類實現pdf文件的數據解析;因此,可使“pdf文件數據采集器”繼承“pdf文件內容解析工具”類,并實現“儀器數據采集器”接口,如下圖所示:
適配器的作用是,繼承現有的類,通過實現接口,擴展其用途。
類適配器繼承源類,由于子類僅能繼承一個父類,因此被繼承的源類實現目標接口的方法多少也可以算做適配程度的高低。
二、示例代碼
接口:
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