一、場(chǎng)景描述
“儀器數(shù)據(jù)采集器”包含采集數(shù)據(jù)以及發(fā)送數(shù)據(jù)給服務(wù)器兩行為,則可定義“儀器數(shù)據(jù)采集器”接口,定義兩方法“采集數(shù)據(jù)capture”和“發(fā)送數(shù)據(jù)senddata”。
“pdf文件數(shù)據(jù)采集器”實(shí)現(xiàn)時(shí),要實(shí)現(xiàn)“儀器數(shù)據(jù)采集器”接口,實(shí)現(xiàn)“采集數(shù)據(jù)”方法;目前有“pdf文件內(nèi)容解析工具”類pdffileextractor,該類實(shí)現(xiàn)pdf文件的數(shù)據(jù)解析;因此,可使“pdf文件數(shù)據(jù)采集器”繼承“pdf文件內(nèi)容解析工具”類,并實(shí)現(xiàn)“儀器數(shù)據(jù)采集器”接口,如下圖所示:
適配器的作用是,繼承現(xiàn)有的類,通過(guò)實(shí)現(xiàn)接口,擴(kuò)展其用途。
類適配器繼承源類,由于子類僅能繼承一個(gè)父類,因此被繼承的源類實(shí)現(xiàn)目標(biāo)接口的方法多少也可以算做適配程度的高低。
二、示例代碼
接口:
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 ; } } |
調(diào)用示例:
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); } } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/mahongbiao/p/8626610.html