Reputation: 6637
I read about visitor pattern at http://en.wikipedia.org/wiki/Visitor_pattern
Initial understanding of this pattern created impression that visitor pattern is same as Bridge/Strategy pattern.
So is that specific example creating such impression ? Can someone explain the difference; possibaly with unambiguous example in Java ?
Upvotes: 0
Views: 260
Reputation: 662
Bridge:
Bridge decouples abstraction from implementation. Both abstraction and implementation can vary independently.
If you are looking for examples, have a look at tutorialspoint article.
Visitor:
Visitor lets you define a new operation without changing the classes of the elements on which it operates.
From GOF definition:
Allows for one or more operation to be applied to a set of objects at runtime, decoupling the operations from the object structure.
The implementation proceeds as follows.
Visitor
class hierarchy that defines a pure virtual visit()
method in the abstract base class for each concrete derived class in the aggregate node hierarchy. visit()
method accepts a single argument - a pointer or reference to an original Element derived class.Visitor
hierarchy. The visit
() methods declared in the Visitor base class are now defined in each derived subclass by allocating the "type query and cast" code in the original implementation to the appropriate overloaded visit() method.accept()
method to the base class of the Element hierarchyFor working java code, have a look at tutorials point article and dzone article.
Strategy:
Strategy allows to switch from one algorithm to other algorithm (from a family of algorithms) dynamically at run time.
Have a look at this SE question for more details.
Real World Example of the Strategy Pattern
Upvotes: 0
Reputation: 10003
From the GOF book, the intents are very different:
Visitor - Object Behavioral - Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Bridge - Object Structural - Decouple an abstraction from its implementation so that the two can vary independently.
Strategy - Object Behavioral - Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
There are lots of Java example around.
Upvotes: 1