The Design of Software (CLOSED)

A public forum for discussing the design of software, from the user interface to the code architecture. Now closed.

The "Design of Software" discussion group has been merged with the main Joel on Software discussion group.

The archives will remain online indefinitely.

Decorator Pattern

I'm looking at the sample chapter of Head First Design Patterns available here:

The chapter is discussing the Decorator pattern, and I'm a bit confused with their example. 

On page 92 (15 in the sample pdf), there's a class diagram for the CondimentDecorator pattern. I don't understand why we only needed to put getDescription() in the CondimentDecorator class, and not for cost().

Nathan Send private email
Thursday, March 17, 2005
Is it because CondimentDecorator is abstract?

Subclasses of CondimentDecorator will be forced to implement cost() because they extend CondimentDecorator, which extends Beverage, in which cost() is an abstract method.

On the other hand CondimentDecorator overrides getDescription() to force its subclasses to implement that method (otherwise they could rely on the default behavior in Beverage, but apparently CondimentDecorators are supposed return an extended description).
Nate Silva Send private email
Thursday, March 17, 2005
Read page 95. There you will see the more important details of the inheritance hierarchi.

In Beverage (abstract class) getDescription() is implemented but cost() is abstract.

CondimentDecorator (abstract class) doesn't want getDescription() to be implemented so it declares it abstract. This forces any children of CondimentDecorator who want to be non-abstract to (re-)implement both cost() and getDescription().

Now cost() doesn't need to be declared in CondimentDecorator because it has been declared in it's parent class and it doesn't wish to override the properties that the base class Beverage provides in cost() (that is cost() being abstract).

I just realize that I've said the same as Nate Silva. Well, hope it helps :)
Peter Monsson Send private email
Thursday, March 17, 2005
So... because Beverage has getDescription() implemented, then CondimentDecorator has to override it, because CondimentDecorator's subclasses need to produce a different result.  Since cost() was not implemented in Beverage, then it doesn't have to be touched in any of the classes that wrap CondimentDecorator. 

getDescription() --> subclasses are ignoring what's in Beverage, and implementing their own.
cost() --> subclasses are using what's in Beverage's subclasses, and modifying it.

Is that right?
Nathan Send private email
Thursday, March 17, 2005

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
Powered by FogBugz