I believe to understand the intent of Decorator and Visitor design pattern.
Though i can list following differences
When i think deep down, i cannot convince myself what is the real difference between the two.
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.
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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With