1. Scene description
Connected with "Java Design Pattern (I) Factory Pattern"
One disadvantage of the factory model is that it destroys the principle of closedness of the class. For example, if you need to add data collection for Word files, follow the following steps:
Step 2 modified the factory class. If the factory class needs to be modified for each additional implementation class, then this is unreasonable.
The solution is to use abstract factory classes, create its factory class for each implementation class, and add factory interfaces so that each factory class implements the interface.
After using the abstract factory, the above steps are changed to:
After modification, since the factory class is abstracted and the factory interface is defined, the original code is no longer necessary to be modified when adding the new implementation class, and the original implementation is not destroyed.
As shown in the figure below:
2. Sample code
Instrument data acquisition interface:
package lims.designpatterndemo.abstractfactorydemo;public interface EquipmentDataCapture { public String capture(String filePath);}PDF file collection class:
package lims.designpatterndemo.abstractfactorydemo;public class PdfFileCapture implements EquipmentDataCapture{ @Override public String capture(String filePath) { return "PDF file content"; }}Excel file collection class:
package lims.designpatterndemo.abstractfactorydemo;public class ExcelFileCapture implements EquipmentDataCapture{ @Override public String capture(String filePath) { return "Excel File Content"; }}Abstract factory, i.e. factory interface:
package lims.designpatterndemo.abstractfactorydemo;public interface EquipmentDataCaptureFactory { public EquipmentDataCapture getCapture(); }PDF file collection factory:
package lims.designpatterndemo.abstractfactorydemo;public class PdfFileCaptureFactory implements EquipmentDataCaptureFactory { @Override public EquipmentDataCapture getCapture() { return new PdfFileCapture(); }}Excel file collection factory:
package lims.designpatterndemo.abstractfactorydemo;public class ExcelFileCaptureFactory implements EquipmentDataCaptureFactory { @Override public EquipmentDataCapture getCapture() { return new ExcelFileCapture(); }}Call example:
package lims.designpatterndemo.abstractfactorydemo;public class AbstractFactoryDemo { public static void main(String[] args) { EquipmentDataCaptureFactory fabric = new PdfFileCaptureFactory(); fabric = new ExcelFileCaptureFactory(); EquipmentDataCapture capture = fabric.getCapture(); String fileContent = capture.capture(""); System.out.println(fileContent); }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.