如何保持干净的Java API

时间:2014-06-20 02:59:54

标签: java

我试图像这样设计一个Java API:

package core;

public abstract class GraphNode {
    public void add(Condition... conditions) {
        // check conditions isn't null, and translate them into a Map

        this.addCore(translatedConditions, new TraversalContext());
    }

    protected abstract void addCore(Map<String, Condition> conditions, TraversalContext traversalContext);
}

问题在于我需要我的具体实现能够递归地将控制传递到图中的后续节点。像这样:

package core.nodes;

public final class ConcreteGraphNode extends GraphNode {
    @Override
    protected void addCore(Map<String, Condition> conditions, TraversalContext traversalContext) {
        if (conditions.size() == 0) {
            // recursion done
            return;
        }

        // remove the appropriate condition, modify the traversal context, create or find the next node in the graph

        // pass the call on recursively
        nextNode.addCore(conditions, traversalContext);
    }

}

我的动机有三个:

  1. 通过公共API调用时,仅进行一次参数检查的成本。从那时起,所有递归都发生在非公共API上,因此可以跳过(或者只是断言)参数验证。
  2. 启用非公共API以获取额外的上下文参数,该参数在公共API中没有业务,因为它是一个实现细节。
  3. 仅在core包中包含最小抽象类型,并使用单独的包(core.nodes)来实现这些抽象的实现。
  4. 然而,Java的可访问性修饰符似乎无法适应这种情况。通过在一个单独的包中,我不能再调用我的超类声明的protected成员。换句话说,无法调用nextNode.addCore中的ConcreteGraphNode

    我想知道是否有一些优雅的方法,并不要求我将我的实施类移到我的core包裹中?

0 个答案:

没有答案