Chapter 3. The Decorator Pattern: Decorating Objects

Images

Just call this chapter “Design Eye for the Inheritance Guy.” We’ll re-examine the typical overuse of inheritance and you’ll learn how to decorate your classes at runtime using a form of object composition. Why? Once you know the techniques of decorating, you’ll be able to give your (or someone else’s) objects new responsibilities without making any code changes to the underlying classes.

Welcome to Starbuzz Coffee

Starbuzz Coffee has made a name for itself as the fastest growing coffee shop around. If you’ve seen one on your local corner, look across the street; you’ll see another one.

Because they’ve grown so quickly, they’re scrambling to update their ordering systems to match their beverage offerings.

When they first went into business they designed their classes like this...

Images
Images

In addition to your coffee, you can also ask for several condiments like steamed milk, soy, and mocha (otherwise known as chocolate), and have it all topped off with whipped milk. Starbuzz charges a bit for each of these, so they really need to get them built into their order system.

Here’s their first attempt...

Images
Images
Images

Well, let’s give it a try. Let’s start with the Beverage base class and add instance variables to represent whether or not each beverage has milk, soy, mocha, and whip...

Images

Now let’s add in the subclasses, one for each beverage on the menu:

Images
Images

The Open-Closed Principle

We’re on to one of the most important design principles:

Images
Images

Come on in; we’re open. Feel free to extend our classes with any new behavior you like. If your needs or requirements change (and we know they will), just go ahead and make your own extensions.

Images

Sorry, we’re closed. That’s right, we spent a lot of time getting this code correct and bug free, so we can’t let you alter the existing code. It must remain closed to modification. If you don’t like it, you can speak to the manager.

Our goal is to allow classes to be easily extended to incorporate new behavior without modifying existing code. What do we get if we accomplish this? Designs that are resilient to change and flexible enough to take on new functionality to meet changing requirements.

Note

While it may seem like a contradiction, there are techniques for allowing code to be extended without direct modification.

Note

Be careful when choosing the areas of code that need to be extended; applying the Open-Closed Principle EVERYWHERE is wasteful and unnecessary, and can lead to complex, hard-to-understand code.

Meet the Decorator Pattern

Okay, we’ve seen that representing our beverage and condiments with inheritance has not worked out very well—we get class explosions and rigid designs, or we add functionality to the base class that isn’t appropriate for some of the subclasses.

So, here’s what we’ll do instead: we’ll start with a beverage and “decorate” it with the condiments at runtime. For example, if the customer wants a Dark Roast with Mocha and Whip, then we’ll:

  1. Take a DarkRoast object

  2. Decorate it with a Mocha object

  3. Decorate it with a Whip object

  4. Call the cost() method and rely on delegation to add up the condiment costs

Okay, but how do you “decorate” an object, and how does delegation come into this? A hint: think of decorator objects as “wrappers.” Let’s see how this works...

Images

Constructing a drink order with Decorators

  1. We start with our DarkRoast object.

    Images
  2. The customer wants Mocha, so we create a Mocha object and wrap it around the DarkRoast.

    Images
  3. The customer also wants Whip, so we create a Whip decorator and wrap Mocha with it.

    Images
  4. Now it’s time to compute the cost for the customer. We do this by calling cost() on the outermost decorator, Whip, and Whip is going to delegate computing the cost to the objects it decorates. And so on. Let’s see how this works:

    Images

Okay, here’s what we know about Decorators, so far...

Images
Note

Now let’s see how this all really works by looking at the Decorator Pattern definition and writing some code.

The Decorator Pattern defined

Let’s first take a look at the Decorator Pattern description:

While that describes the role of the Decorator Pattern, it doesn’t give us a lot of insight into how we’d apply the pattern to our own implementation. Let’s take a look at the class diagram, which is a little more revealing (on the next page we’ll look at the same structure applied to the beverage problem).

Images

Decorating our Beverages

Let’s rework our Starbuzz beverages using the Decorator pattern...

Images

Cubicle Conversation

Some confusion over Inheritance versus Composition

Images

Sue: What do you mean?

Mary: Look at the class diagram. The CondimentDecorator is extending the Beverage class. That’s inheritance, right?

Sue: True. I think the point is that it’s vital that the decorators have the same type as the objects they are going to decorate. So here we’re using inheritance to achieve the type matching, but we aren’t using inheritance to get behavior.

Mary: Okay, I can see how decorators need the same “interface” as the components they wrap because they need to stand in place of the component. But where does the behavior come in?

Sue: When we compose a decorator with a component, we are adding new behavior. We are acquiring new behavior not by inheriting it from a superclass, but by composing objects together.

Mary: Okay, so we’re subclassing the abstract class Beverage in order to have the correct type, not to inherit its behavior. The behavior comes in through the composition of decorators with the base components as well as other decorators.

Sue: That’s right.

Mary: Oh, I get it! And because we are using object composition, we get a whole lot more flexibility about how to mix and match condiments and beverages. Very slick.

Sue: Yes, if we rely on inheritance, then our behavior can only be determined statically at compile time. In other words, we get only whatever behavior the superclass gives us or that we override. With composition, we can mix and match decorators any way we like... at runtime.

Mary: I get it—we can implement new decorators at any time to add new behavior. If we relied on inheritance, we’d have to go in and change existing code any time we wanted new behavior.

Sue: Exactly.

Mary: I just have one more question: if all we need to inherit is the type of the component, how come we didn’t use an interface instead of an abstract class for the Beverage class?

Sue: Well, remember, when we got this code, Starbuzz already had an abstract Beverage class. Traditionally the Decorator Pattern does specify an abstract component, but in Java, obviously, we could use an interface. But we always try to avoid altering existing code, so don’t “fix” it if the abstract class will work just fine.

New barista training

Make a picture for what happens when the order is for a “double mocha soy latte with whip” beverage. Use the menu to get the correct prices, and draw your picture using the same format we used earlier (from a few pages back):

Images
Images

Writing the Starbuzz code

It’s time to whip this design into some real code.

Let’s start with the Beverage class, which doesn’t need to change from Starbuzz’s original design. Let’s take a look:

Images
Images

Beverage is simple enough. Let’s implement the abstract class for the Condiments (the Decorator) as well:

Images

Coding beverages

Now that we’ve got our base classes out of the way, let’s implement some beverages. We’ll start with Espresso. Remember, we need to set a description for the specific beverage and also implement the cost() method.

Images

Coding condiments

If you look back at the Decorator Pattern class diagram, you’ll see we’ve now written our abstract component (Beverage), we have our concrete components (HouseBlend), and we have our abstract decorator (CondimentDecorator). Now it’s time to implement the concrete decorators. Here’s Mocha:

Images

Serving some coffees

Congratulations. It’s time to sit back, order a few coffees, and marvel at the flexible design you created with the Decorator Pattern.

Here’s some test code to make orders:

Images
Images

Real World Decorators: Java I/O

The large number of classes in the java.io package is... overwhelming. Don’t feel alone if you said “whoa” the first (and second and third) time you looked at this API. But now that you know the Decorator Pattern, the I/O classes should make more sense since the java.io package is largely based on Decorator. Here’s a typical set of objects that use decorators to add functionality to reading data from a file:

Images

Decorating the java.io classes

BufferedInputStream and ZipInputStream both extend FilterInputStream, which extends InputStream. InputStream acts as the abstract decorator class:

Images

You can see that this isn’t so different from the Starbuzz design. You should now be in a good position to look over the java.io API docs and compose decorators on the various input streams.

You’ll see that the output streams have the same design. And you’ve probably already found that the Reader/Writer streams (for character-based data) closely mirror the design of the streams classes (with a few differences and inconsistencies, but close enough to figure out what’s going on).

Java I/O also points out one of the downsides of the Decorator Pattern: designs using this pattern often result in a large number of small classes that can be overwhelming to a developer trying to use the Decorator-based API. But now that you know how Decorator works, you can keep things in perspective and when you’re using someone else’s Decorator-heavy API, you can work through how their classes are organized so that you can easily use wrapping to get the behavior you’re after.

Writing your own Java I/O Decorator

Okay, you know the Decorator Pattern, you’ve seen the I/O class diagram. You should be ready to write your own input decorator.

How about this: write a decorator that converts all uppercase characters to lowercase in the input stream. In other words, if we read in “I know the Decorator Pattern therefore I RULE!” then your decorator converts this to “i know the decorator pattern therefore i rule!”

Images
Images

Test out your new Java I/O Decorator

Write some quick code to test the I/O decorator:

Images

Give it a spin:

Images

Inline Tools for your Design Toolbox

You’ve got another chapter under your belt and a new principle and pattern in the toolbox.

Images
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset