Liskov Substitution Principle and the Decorator Pattern

From A Learning Guide to Design Patterns this question is asked about the decorator:

In the Implementation section of the Decorator Pattern, the authors write: A decorator object’s interface must conform to the interface of the component it decorates.

Now consider an object A, that is decorated with an object B. Since object B “decorates” object A, object B shares an interface with object A. If some client is then passed an instance of this decorated object, and that method attempts to call a method in B that is not part of A’s interface, does this mean that the object is no longer a Decorator, in the strict sense of the pattern? Furthermore, why is it important that a decorator object’s interface conforms to the interface of the component. it decorates?

http://www.industriallogic.com/papers/learning.html

During our last design patterns study group we decided the Liskov Substitution Principle applies to this situation and that the Decorator Pattern must follow LSP. So, in the strict sense of the pattern, this is not a true decorator.

Anyone care to tell me if that is right or wrong?

Can’t remember what the Liskov Substitution Principle is?

Let q(x) be a property provable about objects x of type T. Then q(y) should be true for objects y of type S where S is a subtype of T.

Thus, Liskov and Wing’s notion of “subtype” is based on the notion of substitutability; that is, if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program (e.g., correctness).

http://en.wikipedia.org/wiki/Liskov_Substitution_Principle

Wow, that’s pretty heavy… In Agile Development, Robert C. Martin says it more succinctly:

Subtypes must be substitutable for their base types

Agile Software Development, Principles, Patterns, and Practices

So there you have it, please give me your thoughts.

One Response to “Liskov Substitution Principle and the Decorator Pattern”

  1. Thanks for posting this, hearing people say Liskov Substitution Principle with no context makes my brain ‘asplode’.

Leave a Reply