Difference between decorator design pattern and visitor design pattern

Tilak picture Tilak · Feb 20, 2012 · Viewed 11.3k times · Source

I believe to understand the intent of Decorator and Visitor design pattern.

Though i can list following differences

  1. Decorator works on an object, Visitor works on composite structure,
  2. Decorator is Structural design pattern, visitor is Behavioral design pattern.

When i think deep down, i cannot convince myself what is the real difference between the two.

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Feb 20, 2012

Well, they are actually as different as they can be!

You use Decorator when you want to enhance existing object with some new, more-or-less transparent functionality like validation or caching. See example here: Should I extend ArrayList to add attributes that isn't null?

Visitor on the other hand is used when you have a hierarchy of classes and want to run different method based on concrete type but avoiding instanceof or typeof operators. See real-life example: Is This Use of the "instanceof" Operator Considered Bad Design?

Decorator works on an object, Visitor works on composite structure,

Visitor works on an inheritance hierarchy, Composite is a different GoF design pattern.

Decorator is Structural design pattern, visitor is Behavioral design pattern.

True, but it doesn't really help in understanding how they work?

See also