Java設(shè)計模式之工廠模式
一、場景描述
儀器數(shù)據(jù)文件的格式包含Pdf、Word、Excel等多種,不同種格式的文件其數(shù)據(jù)的采集方式不同,因此定義儀器數(shù)據(jù)采集接口,并定義PDF、Excel等不同的數(shù)據(jù)采集類實現(xiàn)該接口。
通過工廠類,調(diào)用不同的方法,獲取不同的儀器數(shù)據(jù)采集類,調(diào)用接口方法即可。
如不使用工廠模式,則需要new不同的采集類對象,使用工廠模式則隱藏了new的創(chuàng)建方式。
如下圖所示:
二、示例代碼
儀器數(shù)據(jù)采集接口:
package lims.designpatterndemo.factorydemo; public interface EquipmentDataCapture { public String capture(String filePath); }
PDF文件數(shù)據(jù)采集類:
package lims.designpatterndemo.factorydemo; public class PdfFileCapture implements EquipmentDataCapture{ @Override public String capture(String filePath) { return "PDF file content"; } }
Excel文件數(shù)據(jù)采集類:
package lims.designpatterndemo.factorydemo; public class ExcelFileCapture implements EquipmentDataCapture{ @Override public String capture(String filePath) { return "Excel File Content"; } }
工廠類:
package lims.designpatterndemo.factorydemo; public class EquipmentDataCaptureFactory { public static EquipmentDataCapture getPdfFileCapture(){ return new PdfFileCapture(); } public static EquipmentDataCapture getExcelFileCapture(){ return new ExcelFileCapture(); } }
調(diào)用示例:
package lims.designpatterndemo.factorydemo; public class FactoryDemo { public static void main(String[] args) { EquipmentDataCapture edc = EquipmentDataCaptureFactory.getPdfFileCapture(); edc = EquipmentDataCaptureFactory.getExcelFileCapture(); String fileContent = edc.capture(""); System.out.println(fileContent); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
apollo與springboot集成實現(xiàn)動態(tài)刷新配置的教程詳解
這篇文章主要介紹了apollo與springboot集成實現(xiàn)動態(tài)刷新配置,本文分步驟給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06idea 創(chuàng)建 maven web 工程流程(圖文教程)
這篇文章主要介紹了idea 創(chuàng)建 maven web 工程流程(圖文教程),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05淺談mybatisPlus的Ipage分頁和map參數(shù)的問題
這篇文章主要介紹了mybatisPlus的Ipage分頁和map參數(shù)的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12Spring中使用騰訊云發(fā)送短信驗證碼的實現(xiàn)示例
本文主要介紹了Spring?中?使用騰訊云發(fā)送短信驗證碼,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03淺談Spring Cloud下微服務(wù)權(quán)限方案
這篇文章主要介紹了淺談Spring Cloud下微服務(wù)權(quán)限方案,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06