gpt4 book ai didi

java - 在这种场景下我应该使用什么样的设计?

转载 作者:行者123 更新时间:2023-12-02 01:02:50 24 4
gpt4 key购买 nike

我是设计软件的新手,我正在尝试构建一个类似树的结构。
我有一个像这样的空界面:

interface Node{
}

两个类NodeANodeB实现了这个接口(interface),并且都有一些特定的属性。除了这些都是节点之外,它们没有任何共同点。

class A implements Node {
public String a;
public A(String a){
this.a = a;
}
}

class B implements Node {
public int a = 5;
public String z = "xyz";

public B(int a,String z){
this.a = a;
this.z = z;
}
}

我有一个class Parse,它根据某些条件创建上述类的实例。

class Parse {
List<Boolean> l;
private static int i=0;
Parse(List<Boolean> l){
this.l = l;
}

private Node parseA() {
return new A(/* param */); // Assume some parameters here
}

private Node parseB() {
return new B(/* param */); // Assume some parameters here
}

private boolean getNextState(){
return l.get(i++);
}

public Node parse(){
boolean x = getNextState();
if(x){
return parseA();
}
else{
return parseB();
}
}
}

驱动程序类别:

public class Test {
public static void main(String[] args) {
List<Boolean> l = Arrays.asList(true,false); // so on...
Parse p = new Parse(l);
Node b = p.parse(); // not sure if its NodeA or NodeB
}
}

构建树后,我计划使用访问者模式来检索一些属性并执行一些操作。

So at last, when i get a Node b, i want to access its attributes (of NodeA or NodeB), which i know cant be done as Polymorphism doesnt work that way.

我认为使用 instanceof 梯子和类型转换并不是正确的解决方案。
很抱歉这个愚蠢的问题,但作为设计新手,我不知道下一步该做什么。

如何解决这一设计问题呢?任何人都可以为此共享一个小型设计结构,假设该结构会变得更大并且有足够的不同节点。 [可能是 Java Generics 在这里提供帮助]

注意:改变上面的设计是可以的,但如果可能的话,我们希望提供一个小示例代码。

最佳答案

正如您所提到的,此处可以使用访客模式。

interface Node {
<T> T accept(NodeVisitor<T> visitor);
}

class A implements Node {
public String a;
public A(String a){
this.a = a;
}

@Override
public <T> T accept(NodeVisitor<T> visitor) {
return visitor.visit(this);
}
}

class B implements Node {
public int a = 5;
public String z = "xyz";

public B(int a,String z){
this.a = a;
this.z = z;
}

@Override
public <T> T accept(NodeVisitor<T> visitor) {
return visitor.visit(this);
}
}

interface NodeVisitor<T> {
T visit(A node);
T visit(B node);
}

然后通过实现相应的访问者来定义特定的操作:

    NodeVisitor<Integer> visitor = new NodeVisitor<Integer>() {
@Override
public Integer visit(A node) {
// TODO do something with A node
return null;
}

@Override
public Integer visit(B node) {
// TODO do something with B node
return null;
}
};

然后调用接受:

Node node = ...;
Integer result = node.accept(visitor);

关于java - 在这种场景下我应该使用什么样的设计?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60447599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com