一、场景描述
工厂模式有一缺点,就是破坏了类的封闭性原则。例如,如果需要增加Word文件的数据采集,此时按以下步骤操作:
步骤2修改了工厂类,如果每增加一实现类都需要修改工厂类,那么这样就不合理了。
解决办法是使用抽象工厂类,为每一个实现类都创建其工厂类,并增加工厂接口,使各工厂类实现该接口。
使用抽象工厂后,上述步骤更改为:
修改后,由于对工厂类进行了抽象,定义了工厂接口,因此新增实现类时不再需要修改原有代码,不破坏原有实现。
如下图所示:
二、示例代码
仪器数据采集接口:
package lims.designpatterndemo.abstractfactorydemo;public interface EquipmentDataCapture { public String capture(String filePath);}
PDF文件采集类:
package lims.designpatterndemo.abstractfactorydemo;public class PdfFileCapture implements EquipmentDataCapture{ @Override public String capture(String filePath) { return "PDF file content"; }}
Excel文件采集类:
package lims.designpatterndemo.abstractfactorydemo;public class ExcelFileCapture implements EquipmentDataCapture{ @Override public String capture(String filePath) { return "Excel File Content"; }}
抽象工厂,即工厂接口:
package lims.designpatterndemo.abstractfactorydemo;public interface EquipmentDataCaptureFactory { public EquipmentDataCapture getCapture(); }
PDF文件采集工厂类:
package lims.designpatterndemo.abstractfactorydemo;public class PdfFileCaptureFactory implements EquipmentDataCaptureFactory { @Override public EquipmentDataCapture getCapture() { return new PdfFileCapture(); }}
Excel文件采集工厂类:
package lims.designpatterndemo.abstractfactorydemo;public class ExcelFileCaptureFactory implements EquipmentDataCaptureFactory { @Override public EquipmentDataCapture getCapture() { return new ExcelFileCapture(); }}
调用示例:
package lims.designpatterndemo.abstractfactorydemo;public class AbstractFactoryDemo { public static void main(String[] args) { EquipmentDataCaptureFactory facotry = new PdfFileCaptureFactory(); facotry = new ExcelFileCaptureFactory(); EquipmentDataCapture capture = facotry.getCapture(); String fileContent = capture.capture(""); System.out.println(fileContent); }}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VeVb武林网。
新闻热点
疑难解答
图片精选