Welcome to OGeek Q&A 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 Reply

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...