Iterating hierarchy of nodes - Visitor and Composite?

寵の児 提交于 2019-12-04 05:04:58

I have something very similar implemented for our system. I wanted a way to compose hierarchy of geometrical object and render them into the volume. I used composite pattern to compose my description (root was Node and then derived child was compositeNode (list of Nodes).

CompositeNode has method accept() which accepts a visitor (Visitor) and then inside the accept() you do visitor->visit(this).

Thus your visitor hierarchy has base class as NodeVisitor and derived visitors like RenderVisitor (renders objects), ReportVisitor (dumped node info into text). Your base class will need to accept both base and specialized node types.

So yes, combo works and I have working code but I agree that design takes more effort than what you would read online (Wiki or toy example).

Hope this helps

Here's a simple example:

struct NodeVisitor;

struct Node
{
  virtual ~Node() {}
  virtual void accept(NodeVisitor &v);
};

struct CompositeNode : public Node
{
  virtual void accept(NodeVisitor &v);
  std::list<NodePtr> nodes_;
};

struct NodeVisitor
{
  virtual ~NodeVisitor() {}
  virtual void visit(Node &n) = 0;
  virtual void visit(CompositeNode &cn)
  {
    for(std::list<NodePtr>::iterator it = cn.nodes_.begin(), end = cn.nodes_.end(); it != end; ++it)
    {
      (*it)->accept(*this);
    }
  }
};

If you want your visitor also to know the structure of the tree (e.g. the depth it is visiting or the path from the tree root) you could consider using the hierarchical visitor pattern. This is described somewhat lengthy at c2.com wiki

It also shows how to skip an 'uninteresting' branch.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!