Loading... Cancel

Visitor Design pattern to traverse hierarchical object structure. R

June 1st, 2007

Those who know about visitor design pattern, i am not triggering my write up for them. but those who didn’t know about this or heard but always ignored i am writing for them.

Visitor design patter is used to traverse through the object structure. it is used to separate the iterating logic from the object.

Let’s imagine, you have the following object structure :

class Tree {

private List mBranches;

public List getBranches() {

return mBranches;

}

}

how we usually iterate through this list of objects, lets think like following code -

// ….

final List branches = tree.getBranches();

for (final Branch branch : branches) {

// …

}

// …

visitor design pattern emphases API designer to hide underlying object structure and iterating logic. now let’s see how we can implement the above example using visitor design pattern:

interface Visitor {

void visit(final Branch pBranch);

}

interface Visitable {

void accept(final Visitor pVisitor);

}

class Tree implements Visitable {

// … previous code

public void visit(final Visitor pVisitor) {

for (final Branch branch : mBranches) {

pVisitor.visit(branch);

}

}

}

now my concern is to make it “n” depth. so it will become a real tree with “n” depth, where can traverse branches and leafs. who is it possible over visitor dp.

here is simple extension over visitor patter, which will enable visitor to visit “n” depth hierarchical object structure.

let’s define our interfaces:

interface Visitor {

void visit(final int pDepth, final TreeItem pItem);

}

interface Visitable {

void accept(final Visitor pVisitor);

}

our tree class:

class Tree implements Visitable {

private TreeItem mRootItem;

// … setter getter

class TreeItem {

private String name;

// .. Setter getter

private List
mTreeItems;

// .. Setter getter

}

public void accept(final Visitor pVisitor) {

visitRecursivlyTreeItem(0, pVisitor, mRootItem);

}

private visitRecursivlyTreeItem(int pLevel, final Visitor pVisitor, final TreeItem pItem) {

pVisitor.visit(pLevel, pItem);

for (final TreeItem item : pVisitor.getTreeItems()) {

visitRecursivlyTreeItem(pLevel + 1, pVisitor, pItem);

}

}

}

That’s all :)

Total 1 response found

Close
  •   Ricky Clarkson

    Thu Jan 70 06:33

    It's worth pointing out that this pattern is invisible in languages that support multiple dynamic dispatch, and that even in Java there are other ways of implementing it.
    Also, what you've defined is an iterator over a tree, not a visitor. There's only one 'visit' method, which is a good sign of that.