Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between decorator design pattern and visitor design pattern

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.

like image 845
Tilak Avatar asked Feb 20 '12 15:02

Tilak


People also ask

What is the difference between decorator and Proxy Pattern?

Decorator Pattern Although Proxy and Decorator patterns have similar structures, they differ in intention; while Proxy's prime purpose is to facilitate ease of use or controlled access, a Decorator attaches additional responsibilities. Both Proxy and Adapter patterns hold a reference to the original object.

Which design pattern is usually used with visitor design pattern?

Visitor design pattern is one of the behavioral design patterns. It is used when we have to perform an operation on a group of similar kind of Objects. With the help of visitor pattern, we can move the operational logic from the objects to another class.

What is the difference between decorator and Strategy pattern?

The strategy pattern allows you to change the implementation of something used at runtime. The decorator pattern allows you augment (or add to) existing functionality with additional functionality at run time.

What is the difference between decorator and adapter pattern?

Decorator Pattern says wrap an original object and add additional features in the wrapper object. So structurally speaking - Wrappers follow decorator pattern. Adapter pattern says changing one object by creating an instance of it and adding functionalities to it.


1 Answers

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

  • Examples of GoF Design Patterns in Java's core libraries
  • What's a suitable return type for this Java method?
like image 64
Tomasz Nurkiewicz Avatar answered Sep 21 '22 19:09

Tomasz Nurkiewicz