2012-12-06 105 views
0

我有一個樹,它由不同類型的對象的例如橫動樹不同類型對象

Tree 
    | \ 
    apple cat 
    | \ 
    dog grass 
     | \ 
     door something 

例如我可以訪問使用Tree.getApple()對象的東西。getGrass()。getSomething ()每一個getter我必須檢查節點是否存在。問題是我使用的結構非常大,我想要一個實用程序類來加速這個過程。

我只想給出的對象的名稱能夠從結構中提取它。例如,在將Something.class作爲參數來遍歷結構之後,如果存在該對象並返回null,則返回該方法。 (我不能在結構中出現多個類,即我只能有一個蘋果對象)

這可能嗎?我可以用什麼來實現它?

回答

3

實現遍歷三個訪客在訪客中實現過濾器。

大致爲:

public class LeafSearching { 

    private final Class typeToFind; 

    private Object result; 

    public LeafSearching(Class typeToFind) { 
     this.typeToFind = typeToFind; 
    } 

    public void visit(Node node) { 
     if (typeToFind.isAssignableFrom(node.getClass())){ 
      result = node; 
      return; 
     } 

     for (Node child : node.getChildren()) { 
      child.accept(this); 
     } 
    } 
} 

interface Node { 

    boolean hasChildren(); 

    List<Node> getChildren(); 

    void accept(LeafSearching ls); 
} 

class Apple implements Node { 
    //... 
} 

class Cat implements Node { 
    // ... 
} 

class TreeRoot implements Node { 

    private Apple apple; 

    private Cat cat; 

    public Apple getApple() { 
     return apple; 
    } 

    public Cat getCat() { 
     return cat; 
    } 

    @Override 
    public boolean hasChildren() { 
     return false; 
    } 

    @Override 
    public List<Node> getChildren() { 
     final List<Node> children = new ArrayList<Node>; 

     if (getApple() != null) { 
      children.add(this.apple); 
     } 

     if (getCat() != null) { 
      children.add(this.cat); 
     } 

     return children; 
    } 

    public void accept(LeafSearching ls) { 
     ls.visit(this); 
    } 
} 
+0

不錯的方式把東西! – acostache

+0

我忘了提及我不能改變結構。所以我想我必須使用某種訪問者。還有一個問題,那就是:我沒有功能來獲取節點的子節點。這些孩子被賦予了作爲類的屬性與setter和getters。所以我猜主要問題是讓孩子們(我想我必須使用反射做這個)? – Ivo

+0

我增強了這個例子。請看TreeRoot中的getChildren。但你當然也可以使用反射。 – ollins

0

我不知道你是如何遍歷數據,但instanceof是你在檢查一類特殊需要這裏的運營商。然後調用適當的方法。

1

我認爲答案是繼承。

爲所有類型的節點創建一個名爲樹節點的類。這將作爲一個超級班。 對於所有的實際類型,如蘋果,草地或其他類似的東西,都會使自己的類擴展treenode類。並且在遍歷方法中,您可以使用instanceof方法檢查每個節點的類型以找到所需類型的節點。

1

我認爲你正在嘗試做的事情可以通過幾種不同的方式實現,如上所述;你可以使用繼承,你可以使用visitor pattern(也許如果你使用Eclipse,你可以像Eclipse ASTVisitor一樣使用它)。

我會說你也可以使用聲明getChild(name)之類的方法的接口來檢查你正在搜索的類的名字並遍歷樹。

這裏的底線是,在我看來,你只需要選擇你想要的方式。