学习完工厂方法模式,模仿写了个demo,加深记忆。原博地址:https://www.cnblogs.com/java-my-life/
情景:导出数据库中内容,可能有word excel形式,又各自有标准和非标准两种格式,这样直接编程需要多个if else。
public class DemoDirect { public static void main(String[] args) { String data = ""; String type = "excel"; String pattern = "standard"; if ("excel".equals(type) && "standard".equals(pattern)) { new ExportStandardExcelFile().export(data); } else if ("excel".equals(type) && "unstandard".equals(pattern)) { new ExportUnStandardExcelFile().export(data); } else if ("word".equals(type) && "standard".equals(pattern)) { new ExportStandardWordFile().export(data); } else if ("word".equals(type) && "unstandard".equals(pattern)) { new ExportUnStandardWordFile().export(data); } else { // .. } } }
需要四个对象。
使用工厂方法模式:
抽象工厂:
public interface ExportFactory { ExportFile factory(String type); }
具体实现工厂:
public class ExportExcelFactory implements ExportFactory { @Override public ExportFile factory(String type) { if ("standard".equals("type")) { return new ExportStandardExcelFile(); } else if ("unstandard".equals("type")) { return new ExportUnStandardExcelFile(); } else { throw new RuntimeException("no such type"); } } }
public class ExportWordFactory implements ExportFactory { @Override public ExportFile factory(String type) { if ("standard".equals("type")) { return new ExportStandardWordFile(); } else if ("unstandard".equals("type")) { return new ExportUnStandardWordFile(); } else { throw new RuntimeException("no such type"); } } }
抽象导出类:
public interface ExportFile { boolean export(String data); }
具体导出类:
public class ExportStandardExcelFile implements ExportFile{ @Override public boolean export(String data) { //业务 return true; } }
public class ExportUnStandardExcelFile implements ExportFile{ @Override public boolean export(String data) { //业务 return true; } }
public class ExportStandardWordFile implements ExportFile{ @Override public boolean export(String data) { //业务 return true; } }
public class ExportUnStandardWordFile implements ExportFile{ @Override public boolean export(String data) { //业务 return true; } }
测试:
public class Demo { public static void main(String[] args) { String data=""; ExportFactory exportFactory=new ExportExcelFactory(); ExportFile exportFile = exportFactory.factory("standard"); exportFile.export(data); } }
总结:直接编程,需要一个接口,四个对象,客户端选择一个对象。
简单工厂,一个接口,两个对象,客户端传入2个参数(形式,格式)
工厂方法,2个接口,四个对象,客户端传入一个参数。每个子工厂其实是个简单工厂模式。