Saturday, February 27, 2010

Design Patterns: Decorator vs Chain of Responsibility

I am teaching a class this weekend on Design Patterns and the students are recognizing that many of the patterns start to look alike. Since the patterns rely on good OO principles like coding to the interface, then this is true.

However, someone was asking for a more detailed description of the differences between the Chain of Responsibility and Decorator patterns. I gave them my take on it but decided to do a little research on the topic.

Admittedly, this was very little research and I still believe my original answer holds true...
I believe that the biggest difference is that the client should have no idea that a Decorator is being used as opposed to the target object. However, they certainly know if they are using a Chain of Responsibility because the target object is passed along the chain.
I don't think that the primary difference is that the chain can be stopped at any point in the Chain of Responsibility structure while it must proceed to the target object in the Decorator. Would that mean that any Decorator "wrapper" that does not call the next Decorator (or Target) is no longer a Decorator? What if I'm decorating an object to perform some kind of security check and not allow access to the target object?

I do agree that there are similarities in that they both contain a "HAS-A" and an "IS-A". However, the "IS-A" for the decorator must be the same as the target object while the Chain of Responsibility is not.

Then we turned our attention to the Decorator and the Proxy and there again are the similarities. Both must implement the same interface as the target object. But the Decorator has an instance of it's parent type while the Proxy has an instance of the target object. Does that just imply that Decorators can be nested while a Proxy can not?

Continuing to search for these answers...

No comments:

Post a Comment