个人对工厂模式的简单理解:简单工厂模式下,可能一个工厂就要生产好几个“具体实现”,当需要的“具体实现”特别多时,一个工厂就会显得高耦合,需要将“具体实现”分别分发给不同的工厂,把一个工厂分成好几个“术业有专攻”的工厂。
各个工厂要有一个统一的生产接口
/**
* author:lcy
* since 2021/6/25 11:59
* 工厂接口
*/
public interface ExportFactory {
public ExportFile getFactory(String FactoryType);
}
各个工厂再去实现这个生产接口
/**
* author:lcy
* since 2021/6/25 14:02
* 只负责生产HTML格式的工厂
*/
public class ExportHtmlFactory implements ExportFactory{
@Override
public ExportFile getFactory(String FactoryType) {
if("html的工资表格式".equals(FactoryType)){
return new ExportFinancialHtmlFile();
}else if("html的普通格式".equals(FactoryType)){
return new ExportStandardHtmlFile();
}else {
throw new RuntimeException("没有匹配的格式!!!");
}
}
}
/**
* author:lcy
* since 2021/6/25 14:10
* 只负责生产PDF格式的工厂
*/
public class ExportPdfFactory implements ExportFactory{
@Override
public ExportFile getFactory(String FactoryType) {
if("PDF的工资表格式".equals(FactoryType)){
return new ExportFinancialPdfFile();
}else if("PDF的普通格式".equals(FactoryType)){
return new ExportStandardPdfFile();
}else{
throw new RuntimeException("没有匹配的格式!!!");
}
}
}
工厂创建出来了,具体方法要有一个逻辑实现接口
/**
* author:lcy
* since 2021/6/25 12:00
* 工厂产生的实际方法接口
*/
public interface ExportFile {
public boolean export();
}
/**
* author:lcy
* since 2021/6/25 14:03
* HTML工资表形式的具体实现
*/
public class ExportFinancialHtmlFile implements ExportFile{
@Override
public boolean export() {
//导出和具体的业务逻辑
return false;
}
}
/**
* author:lcy
* since 2021/6/25 14:04
* HTML普通格式的具体表现
*/
public class ExportStandardHtmlFile implements ExportFile {
@Override
public boolean export() {
//导出和具体的业务逻辑
return false;
}
}
/**
* author:lcy
* since 2021/6/25 14:04
* PDF普通格式的具体表现
*/
public class ExportStandardPdfFile implements ExportFile{
@Override
public boolean export() {
//导出和具体的业务逻辑
return false;
}
}
/**
* author:lcy
* since 2021/6/25 14:04
* PDF工资表格式的具体表现
*/
public class ExportFinancialPdfFile implements ExportFile{
@Override
public boolean export() {
//导出和具体的业务逻辑
return false;
}
}
使用代码如下
/**
* author:lcy
* since 2021/6/25 14:18
*/
public class Main {
public static void main(String[] args) {
//假如现在需要html格式的文件
//就要先new一个只生成HTML格式的工厂
ExportHtmlFactory factory = new ExportHtmlFactory();
//需要工资表格式html文件
//就传入工资表格式的参数
ExportFile file = factory.getFactory("html的工资表格式");
//干活。。。
file.export();
//假如现在需要PDF格式的文件
//就要先new一个只生成PDF格式的工厂
ExportHtmlFactory factory2 = new ExportHtmlFactory();
//需要工资表格式PDF文件
//就传入工资表格式的参数
ExportFile file2 = factory.getFactory("PDF的工资表格式");
//干活。。。
file.export();
}
}