lExportService;
public static AbstractExportService getExportService(IExportRequest exportRequest) {
if (exportRequest instanceof OrderExportRequest) {
return getOrderExportServiceInstance();
}
if (exportRequest instanceof GeneralExportRequest) {
return getGeneralExportServiceInstance();
}
throw new IllegalArgumentException("Invalid export request type" + exportRequest.getClass().getName());
}
public static OrderExportService getOrderExportServiceInstance() {
// 实际需要考虑并发, 或者通过Spring容器管理实例
if (orderExportService != null) {
return orderExportService;
}
return new OrderExportService();
}
public static GeneralExportService getGeneralExportServiceInstance() {
// 实际需要考虑并发, 或者通过Spring容器管理实例
if (generalExportService != null) {
return generalExportService;
}
return new GeneralExportService();
}
}
客户端使用
现在,可以在客户端使用已有的导出实现了。
public class ExportInstance {
public static void main(String[] args) {
OrderExportRequest orderExportRequest = new OrderExportRequest();
ExportServiceFactory.getExportService(orderExportRequest).export(orderExportRequest);
GeneralExportRequest generalExportRequest = new GeneralExportRequest();
ExportServiceFactory.getExportService(generalExportRequest).export(generalExportRequest);
}
}
现在,订单导出与通用导出能够复用相同的导出流程及导出方法了。
基于接口设计
主要场景是:1. 需要从系统中提炼出更通用的系统; 2. 需要从老系统重构出新的系统而不需要做“剧烈的变更”。有同学可能担心,基于接口设计系统是否显得“过度设计”。在我看来,先设计系统的接口骨架,可以让系统的流程更加清晰自然,更容易理解,也更容易变更和维护。接口及交互设计得足够好,就能更好滴接近“开闭原则”,有需求变更的时候,只是新增代码而不修改原有代码。
基于接口设计需要有更强的整体设计思维,预先思考和建立系统的整体行为规约及交互,而不是走一步看一步。
JDK集合框架是基于接口设计的典范,读者可仔细体味。
基于接口编程
基于接口编程有三个实际层面:基于Interface编程;基于泛型接口编程; 基于Function编程。
基于Interface编程,能够让方法不局限于具体类,更好滴运用到多态,适配不同的对象实例; 基于泛型编程,能够让方法不局限于具体类型,能够适配更多类型;基于Function编程,能够让方法不局限于具体行为,能够根据传入的行为而改变其具体功能变化多样,解耦外部依赖。
小结
通过一个实际的例子阐述了基于接口设计与编程的缘由。基于接口设计与编程,可以使系统更加清晰而容易扩展和变更。