情况
我正在制作一个像这样的图类:
class ImmutableGraph<G> {
Node<G> selectedNode;
private ImmutableGraph(Node<G> initialNode) { selectedNode = initialNode; }
//many more things
}
而且我目前正在使用这样的(嵌套)生成器类
public static class GraphBuilder<B> {
Node<B> currentNode;
public GraphBuilder(B value){ currentNode = new Node(value); }
public ImmutableGraph<B> build(){
return new ImmutableGraph<B>(currentNode);
}
//many more things
}
使用(嵌套的)节点类
private static class Node<N> {
private final N value;
Array<Nodes<N>> neighbours;
public Node(N v){ value = v; }
//many more things
}
问题
我找不到使用生成器实例化
ImmutableGraph
的方法,因为返回类型不正确。实际上,编译建议GraphBuilder.build()
应该返回类型ImmutableGraph<Node<B>>
而不是ImmutableGraph<B>
到目前为止,我发现的唯一解决方案是将返回类型更改为
ImmutableGraph<Node<B>>
,但由于所有图(空图除外)都是节点图,因此感觉很愚蠢。 Node
类型也令人困惑,因为用户从不与之交互。编辑:
更正了构建器的工厂方法中的“新”
最佳答案
我认为您的构建方法应return new ImmutableGraph<B>(currentNode);
import java.util.List;
public class ImmutableGraph<G> {
Node<G> selectedNode;
private ImmutableGraph(Node<G> initialNode) {
selectedNode = initialNode;
}
// many more things
public static class GraphBuilder<B> {
Node<B> currentNode;
public GraphBuilder(B value) {
currentNode = new Node<B>(value);
}
public ImmutableGraph<B> build() {
return new ImmutableGraph<B>(currentNode);
}
// many more things
}
private static class Node<N> {
private final N value;
List<Node<N>> neighbours;
public Node(N v) {
value = v;
}
// many more things
}
public static void main(String[] args) {
GraphBuilder<Integer> builder = new GraphBuilder<Integer>(Integer.MAX_VALUE);
ImmutableGraph<Integer> graph = builder.build();
System.out.println(graph.selectedNode.value);
}
}