I am not seeing any difference. Looks like both Patterns are trying to compose objects. Can anyone explain the intentions behind these two patterns?
-
2Have you at least googled for "visitor pattern" and "composite pattern"? Both lead to a complete explanation page on wikipedia. – JB Nizet Jun 28 '12 at 07:38
3 Answers
These patterns are completely different! First of all Composite is a structural patterns, which means it is used to build data structure. Visitor is behavioral pattern, responsible for relationships and behaviors.
To explain it a bit further, you use Composite to build objects tree where all items are subtypes of T
. However one of the subclasses of T
(sort of container) can hold a collection of child T
s. Think of a class Item
than has two subclasses: Product
and Box
. Box
can further hold a collection of Item
s, either products or boxes. These nested boxes can keep even more items, so we are effectively building a tree-like structure.
Visitor is used to emulate virtual calls to avoid instanceof
-like structures. See Is This Use of the "instanceof" Operator Considered Bad Design? for complete example. Visitor can be used together with Composite - like in example above you can traverse the tree if Item
defines accept(ItemVisitor visitor)
method.
I find it very hard to see any similarities between these two.

- 1
- 1

- 334,321
- 69
- 703
- 674
They are different patterns, but they are often used together.
The point of composite is to apply the same operation to a bunch of elements that share an interface. The point of visitor is to extend a bunch of elements with a new operation without changing their implementation nor the caller's implementation. Therefore you often see:
Composite c = new Composite();
Visitor v = new ConcreteVisitor();
c.visit(v);
This way you can keep the implementation of the composite and the classes that are in the composite static, and only vary the kind of Visitor you apply to them.

- 10,165
- 7
- 35
- 52
The Composite is an Object that has a set of operations and a container of objects of itself. The container may or may not contain objects. Operations performed on a Composite will be performed on itself and on all objects it contains. Some people may refer to this as a sort of tree.
The Visitor is a set of objects/operations that work on an established hierarchy of classes. The Visitor allows you to create operations on the hierarchy without having to change the hierarchy. An example would be to create an operation that operates on (visits) several objects in the hierarchy, thus combining work on several objects without having to change their interface.
The 2 patterns are indeed quite different.

- 10,207
- 2
- 20
- 59