如何在Java模块化项目中正确组织接口和实现?

huangapple 未分类评论45阅读模式
英文:

How to properly organize interfaces and implementations in Java modular project?

问题

我正在寻找一种在Java 11模块化项目中正确组织接口和实现的方法。

考虑最简单的情况:有一个接口及其多个实现。意图是仅公开此接口及其工厂方法作为模块API。

MyInterface.java

public interface MyInterface {

  String action(String input);
    
  //--- factory methods

  static MyInterface createSimple(Object argument){
     return new MySimpleImpl(argument);
  }    
    
  static MyInterface createComplex(Object a, Object b){
     return new MyComplexImpl(a,b);
  }
}

MySimpleImpl.java

class MySimpleImpl implements MyInterface { ... }

MyComplexImpl.java

class MyComplexImpl implements MyInterface { ... }

假设根包是 org.company.myproject

因此,module-info.java 仅包含一个导出:exports org.company.myproject;


我看到有几种组织代码的方式,例如显而易见的是:

版本1:
将实现放入嵌套包中并使它们为 public

版本2:
将实现放入根包中并保持其为 package-private

目前我不能偏好任何一个版本,因为第一个版本会强制我在模块内部违反可见性约定,而第二个版本会使根包变得混乱,使其意图不明确。

请帮助我理解如何明确表达我在模块内部和外部的类可见性意图。可能对于这种情况有最佳实践。

英文:

I am looking for a way to properly organize interfaces and implementations in Java 11 modular project.

Considering the simplest case: there is an interface and its multiple implementations. The intention is to expose only this interface and its factory methods as the module API.

MyInterface.java

public interface MyInterface {

  String action(String input);

  //--- factory methods

  static MyInterface createSimple(Object argument){
     return new MySimpleImpl(argument);
  }    

  static MyInterface createComplex(Object a, Object b){
     return new MyComplexImpl(a,b);
  }
}

MySimpleImpl.java

class MySimpleImpl implements MyInterface { ... }

MyComplexImpl.java

class MyComplexImpl implements MyInterface { ... }

Suppose the root package is org.company.myproject.

So module-info.java contains only one export: exports org.company.myproject;


I see several ways to organize the code, for instance the obvious are:

Version 1:
Put implementations into a nested package and make them public.

Version 2:
Put implementations into the root package and keep them package-private.

At the moment I cannot prefer any of the versions, because the first forces me to break visibility contracts inside the module itself, and the second pollutes the root package making its intentions vague.

Please, help me to understand how to precisely express my intentions for the module's classes visibility inside and outside the module both. Probably, there are best practices for this situation.

huangapple
  • 本文由 发表于 2020年4月10日 21:37:44
  • 转载请务必保留本文链接:https://java.coder-hub.com/61141476.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定