Kaushik Lele
Kaushik Lele

Reputation: 6637

Difference between Vistor pattern and Stategy pattern?

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

Answers (2)

Aditya W
Aditya W

Reputation: 662

Bridge:

Bridge decouples abstraction from implementation. Both abstraction and implementation can vary independently.

  1. Create bridge implementer interface
  2. Create concrete bridge implementer classes
  3. Create an abstract class which contains the interface ( Composition is key here)
  4. Create concrete class implementing the abstract class

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.

  1. Create a 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.
  2. Each visit() method accepts a single argument - a pointer or reference to an original Element derived class.
  3. Each operation to be supported is modeled with a concrete derived class of the 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.
  4. Add a single pure virtual accept() method to the base class of the Element hierarchy

For 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

Ray Tayek
Ray Tayek

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

Related Questions