设为首页 加入收藏

TOP

基于接口设计与编程(三)
2018-04-08 08:51:22 】 浏览:442
Tags:基于 接口 设计 编程
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编程,能够让方法不局限于具体行为,能够根据传入的行为而改变其具体功能变化多样,解耦外部依赖。

小结

通过一个实际的例子阐述了基于接口设计与编程的缘由。基于接口设计与编程,可以使系统更加清晰而容易扩展和变更。

首页 上一页 1 2 3 下一页 尾页 3/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Java日志框架:slf4j作用及其实现.. 下一篇使用FastBootWeixin框架快速开发..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目