Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

what ObjectStructure in visitor design pattern is?

I have a question about visitor pattern. What is not clear to me is what is the Object structure shown in the visitor design. from the GOF design pattern book:

ObjectStructure:

  • can enumerate its elements.
  • ObjectStructure: may provide a high-level interface to allow the visitor to visit its elements.
  • ...

Does the second ponint mean I can add the accept method to the ObjectStructure class? [like in the code below]

class ObjectStructure{
    private Collection<Element> collection;
    
    public void accept(Visitor visitor){
        for(Element element: collection)
            element.accept(visitor);
    }
}

Thank you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, you are correct.

The Object Structure can be any container of elements to be visited. Its purpose is just to iterate over the different elements, so what you have is fine. The elements could also be connected by a tree structure, like the Composite pattern.

A unique feature of the Visitor pattern is that the elements to be visited do not require any common hierarchy beyond a shared accept() method. You could visit completely unrelated elements from unconnected sources, with no Object Structure at all (though that probably wouldn't be very useful).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...