You are previewing Head First Design Patterns.

Head First Design Patterns

Cover of Head First Design Patterns by Kathy Sierra... Published by O'Reilly Media, Inc.
  1. Head First Design Patterns
  2. Dedication
  3. A Note Regarding Supplemental Files
  4. Praise for Head First Design Patterns
  5. More Praise for Head First Design Patterns
  6. Praise for the Head First approach
  7. Authors/Developers of Head First Design Patterns
  8. Creators of the Head First series (and co-conspirators on this book)
  9. How to Use This Book: Intro
    1. Who is this book for?
      1. Who should probably back away from this book?
    2. We know what you’re thinking
    3. And we know what your brain is thinking
    4. Metacognition: thinking about thinking
    5. Here’s what WE did
    6. Here’s what YOU can do to bend your brain into submission
    7. Read Me
    8. Tech Reviewers
    9. Acknowledgments
    10. Even more people
  10. 1. Intro to Design Patterns: Welcome to Design Patterns
    1. It started with a simple SimUDuck app
    2. But now we need the ducks to FLY
    3. But something went horribly wrong...
    4. Joe thinks about inheritance...
    5. How about an interface?
      1. What would you do if you were Joe?
    6. The one constant in software development
    7. Zeroing in on the problem...
    8. Separating what changes from what stays the same
    9. Designing the Duck Behaviors
    10. Implementing the Duck Behaviors
    11. Integrating the Duck Behavior
    12. More Integration...
    13. Testing the Duck code
    14. Setting behavior dynamically
    15. The Big Picture on encapsulated behaviors
    16. HAS-A can be better than IS-A
    17. Speaking of Design Patterns...
    18. Overheard at the local diner...
    19. Overheard in the next cubicle...
    20. The power of a shared pattern vocabulary
    21. How do I use Design Patterns?
    22. Tools for your Design Toolbox
    23. Solutions
  11. 2. The Observer Pattern: Keeping your Objects in the know
    1. The Weather Monitoring application overview
    2. Unpacking the WeatherData class
    3. What do we know so far?
    4. Taking a first, misguided SWAG at the Weather Station
    5. What’s wrong with our implementation?
    6. Meet the Observer Pattern
    7. Publishers + Subscribers = Observer Pattern
    8. A day in the life of the Observer Pattern
    9. Five minute drama: a subject for observation
    10. Two weeks later...
    11. The Observer Pattern defined
    12. The Observer Pattern defined: the class diagram
    13. The power of Loose Coupling
    14. Cubicle conversation
    15. Designing the Weather Station
    16. Implementing the Weather Station
    17. Implementing the Subject interface in WeatherData
    18. Now, let’s build those display elements
    19. Power up the Weather Station
    20. Using Java’s built-in Observer Pattern
    21. How Java’s built-in Observer Pattern works
    22. Reworking the Weather Station with the built-in support
    23. Running the new code
    24. The dark side of java.util.Observable
    25. Other places you’ll find the Observer Pattern in the JDK
    26. And the code...
    27. Tools for your Design Toolbox
    28. Exercise Solutions
  12. 3. The Decorator Pattern: Decorating Objects
    1. Welcome to Starbuzz Coffee
    2. The Open-Closed Principle
    3. Meet the Decorator Pattern
    4. Constructing a drink order with Decorators
      1. Okay, here’s what we know so far...
      2. Now let’s see how this all really works by looking at the Decorator Pattern definition and writing some code
    5. The Decorator Pattern defined
    6. Decorating our Beverages
    7. Cubicle Conversation
    8. New barista training
    9. Writing the Starbuzz code
    10. Coding beverages
    11. Coding condiments
    12. Serving some coffees
    13. Real World Decorators: Java I/O
    14. Decorating the classes
    15. Writing your own Java I/O Decorator
    16. Test out your new Java I/O Decorator
    17. Tools for your Design Toolbox
    18. Exercise Solutions
  13. 4. The Factory Pattern: Baking with OO Goodness
    1. Identifying the aspects that vary
    2. But the pressure is on to add more pizza types
    3. Encapsulating object creation
    4. Building a simple pizza factory
    5. Reworking the PizzaStore class
    6. The Simple Factory defined
    7. Franchising the pizza store
      1. We’ve seen one approach...
      2. But you’d like a little more quality control...
    8. A framework for the pizza store
    9. Allowing the subclasses to decide
    10. Let’s make a PizzaStore
    11. Declaring a factory method
      1. Let’s see how it works: ordering pizzas with the pizza factory method
      2. So how do they order?
      3. Let’s check out how these pizzas are really made to order...
    12. We’re just missing one thing: PIZZA!
      1. Our PizzaStore isn’t going to be very popular without some pizzas, so let’s implement them
      2. Now we just need some concrete subclasses... how about defining New York and Chicago style cheese pizzas?
    13. You’ve waited long enough, time for some pizzas!
    14. It’s finally time to meet the Factory Method Pattern
      1. The Creator classes
      2. The Product classes
    15. Another perspective: parallel class hierarchies
    16. Factory Method Pattern defined
    17. A very dependent PizzaStore
    18. Looking at object dependencies
    19. The Dependency Inversion Principle
    20. Applying the Principle
    21. Inverting your thinking...
    22. A few guidelines to help you follow the Principle...
    23. Meanwhile, back at the PizzaStore...
      1. Ensuring consistency in your ingredients
    24. Families of ingredients...
    25. Building the ingredient factories
    26. Building the New York ingredient factory
    27. Reworking the pizzas...
    28. Revisiting our pizza stores
    29. What have we done?
    30. More pizza for Ethan and Joel...
      1. From here things change, because we are using an ingredient factory
    31. Abstract Factory Pattern defined
    32. Factory Method and Abstract Factory compared
    33. Tools for your Design Toolbox
    34. Exercise Solutions
    35. A very dependent PizzaStore
  14. 5. The Singleton Pattern: One of a Kind Objects
    1. The Little Singleton
    2. Dissecting the classic Singleton Pattern implementation
    3. The Chocolate Factory
    4. Singleton Pattern defined
    5. Houston, Hershey, PA we have a problem...
    6. Dealing with multithreading
    7. Can we improve multithreading?
      1. 1. Do nothing if the performance of getInstance() isn’t critical to your application
      2. 2. Move to an eagerly created instance rather than a lazily created one
      3. 3. Use “double-checked locking” to reduce the use of synchronization in getInstance()
    8. Meanwhile, back at the Chocolate Factory...
    9. Congratulations!
    10. Tools for your Design Toolbox
    11. Exercise Solutions
  15. 6. The Command Pattern: Encapsulating Invocation
    1. Free hardware! Let’s check out the Remote Control...
    2. Taking a look at the vendor classes
    3. Cubicle Conversation
      1. Meanwhile, back at the Diner..., or, A brief introduction to the Command Pattern
    4. Let’s study the interaction in a little more detail...
    5. The Objectville Diner roles and responsibilities
    6. From the Diner to the Command Pattern
    7. Our first command object
    8. Using the command object
    9. Creating a simple test to use the Remote Control
    10. The Command Pattern defined
    11. The Command Pattern defined: the class diagram
    12. Assigning Commands to slots
    13. Implementing the Remote Control
    14. Implementing the Commands
    15. Putting the Remote Control through its paces
    16. Time to write that documentation...
      1. What are we doing?
    17. Time to QA that Undo button!
    18. Using state to implement Undo
    19. Adding Undo to the ceiling fan commands
    20. Get ready to test the ceiling fan
    21. Testing the ceiling fan...
    22. Every remote needs a Party Mode!
    23. Using a macro command
    24. More uses of the Command Pattern: queuing requests
    25. More uses of the Command Pattern: logging requests
    26. Tools for your Design Toolbox
    27. Exercise Solutions
  16. 7. The Adapter and Facade Patterns: Being Adaptive
    1. Adapters all around us
    2. Object oriented adapters
    3. If it walks like a duck and quacks like a duck, then it must might be a duck turkey wrapped with a duck adapter...
    4. Test drive the adapter
    5. The Adapter Pattern explained
      1. Here’s how the Client uses the Adapter
    6. Adapter Pattern defined
    7. Object and class adapters
    8. Real world adapters
      1. Old world Enumerators
      2. New world Iterators
      3. And today...
    9. Adapting an Enumeration to an Iterator
      1. Designing the Adapter
      2. Dealing with the remove() method
      3. Writing the EnumerationIterator adapter
    10. And now for something different...
    11. Home Sweet Home Theater
    12. Watching a movie (the hard way)
    13. Lights, Camera, Facade!
    14. Constructing your home theater facade
    15. Implementing the simplified interface
    16. Time to watch a movie (the easy way)
    17. Facade Pattern defined
    18. The Principle of Least Knowledge
    19. How NOT to Win Friends and Influence Objects
      1. Keeping your method calls in bounds...
    20. The Facade and the Principle of Least Knowledge
    21. Tools for your Design Toolbox
    22. Exercise Solutions
  17. 8. The Template Method Pattern: Encapsulating Algorithms
    1. It’s time for some more caffeine
    2. Whipping up some coffee and tea classes (in Java)
    3. Sir, may I abstract your Coffee, Tea?
    4. Taking the design further...
    5. Abstracting prepareRecipe()
    6. What have we done?
    7. Meet the Template Method
    8. Let’s make some tea...
    9. What did the Template Method get us?
    10. Template Method Pattern defined
    11. Hooked on Template Method...
    12. Using the hook
    13. Let’s run the TestDrive
    14. The Hollywood Principle
    15. The Hollywood Principle and Template Method
    16. Template Methods in the Wild
      1. Sorting with Template Method
    17. We’ve got some ducks to sort...
    18. What is compareTo()?
    19. Comparing Ducks and Ducks
    20. Let’s sort some Ducks
    21. The making of the sorting duck machine
    22. Swingin’ with Frames
    23. Applets
    24. Tools for your Design Toolbox
    25. Exercise Solutions
  18. 9. The Iterator and Composite Patterns: Well-Managed Collections
    1. Breaking News: Objectville Diner and Objectville Pancake House Merge
    2. Check out the Menu Items
    3. Lou and Mel’s Menu implementations
    4. What’s the problem with having two different menu representations?
      1. The Java-Enabled Waitress Specification
    5. What now?
    6. Can we encapsulate the iteration?
    7. Meet the Iterator Pattern
    8. Adding an Iterator to DinerMenu
    9. Reworking the Diner Menu with Iterator
    10. Fixing up the Waitress code
    11. Testing our code
    12. What have we done so far?
    13. What we have so far...
    14. Making some improvements...
    15. Cleaning things up with java.util.Iterator
    16. We are almost there...
    17. What does this get us?
    18. Iterator Pattern defined
    19. Single Responsibility
    20. Taking a look at the Café Menu
    21. Reworking the Café Menu code
    22. Adding the Café Menu to the Waitress
    23. Breakfast, lunch AND dinner
    24. What did we do?
    25. We decoupled the Waitress....
    26. ... and we made the Waitress more extensible
    27. But there’s more!
    28. Iterators and Collections
    29. Iterators and Collections in Java 5
    30. Is the Waitress ready for prime time?
    31. Just when we thought it was safe...
    32. What do we need?
    33. The Composite Pattern defined
    34. Designing Menus with Composite
    35. Implementing the Menu Component
    36. Implementing the Menu Item
    37. Implementing the Composite Menu
      1. Fixing the print() method
    38. Getting ready for a test drive...
    39. Now for the test drive...
    40. Getting ready for a test drive...
    41. Flashback to Iterator
    42. The Composite Iterator
    43. The Null Iterator
    44. Give me the vegetarian menu
    45. The magic of Iterator & Composite together...
    46. Tools for your Design Toolbox
    47. Exercise Solutions
  19. 10. The State Pattern: The State of Things
    1. Jawva Breakers
    2. Cubicle Conversation
    3. State machines 101
    4. Writing the code
    5. In-house testing
    6. You knew it was coming... a change request!
    7. The messy STATE of things...
    8. The new design
    9. Defining the State interfaces and classes
    10. Implementing our State classes
    11. Reworking the Gumball Machine
    12. Implementing more states
    13. Let’s take a look at what we’ve done so far...
    14. The State Pattern defined
    15. We still need to finish the Gumball 1 in 10 game
    16. Finishing the game
    17. Demo for the CEO of Mighty Gumball, Inc.
    18. Sanity check...
    19. We almost forgot!
    20. Tools for your Design Toolbox
    21. Exercise Solutions
  20. 11. The Proxy Pattern: Controlling Object Access
    1. Coding the Monitor
    2. Testing the Monitor
    3. The role of the ‘remote proxy’
    4. Adding a remote proxy to the Gumball Machine monitoring code
    5. Remote methods 101
      1. How the method call happens
    6. Java RMI, the Big Picture
      1. Making the Remote service
    7. How does the client get the stub object?
    8. Back to our GumballMachine remote proxy
    9. Getting the GumballMachine ready to be a remote service
    10. Registering with the RMI registry...
    11. Now for the GumballMonitor client...
    12. Writing the Monitor test drive
    13. Another demo for the CEO of Mighty Gumball...
    14. The Proxy Pattern defined
    15. Get ready for Virtual Proxy
    16. Displaying CD covers
    17. Designing the CD cover Virtual Proxy
      1. How ImageProxy is going to work
    18. Writing the Image Proxy
    19. What did we do?
    20. Using the Java API’s Proxy to create a protection proxy
    21. Matchmaking in Objectville
    22. The PersonBean implementation
    23. Five minute drama: protecting subjects
    24. Big Picture: creating a Dynamic Proxy for the PersonBean
    25. Step one: creating Invocation Handlers
    26. Step two: creating the Proxy class and instantiating the Proxy object
    27. Testing the matchmaking service
    28. Running the code...
    29. The Proxy Zoo
    30. Tools for your Design Toolbox
    31. Exercise Solutions
  21. 12. Compound Patterns: Patterns of Patterns
    1. Working together
    2. Duck reunion
    3. What did we do?
    4. A duck’s eye view: the class diagram
    5. The King of Compound Patterns
      1. If Elvis were a compound pattern, his name would be Model-View-Controller, and he’d be singing a little song like this...
    6. Meet the Model-View-Controller
    7. A closer look...
    8. Looking at MVC through patterns-colored glasses
    9. Using MVC to control the beat...
      1. Meet the Java DJ View
      2. The controller is in the middle...
      3. Let’s not forget about the model underneath it all...
    10. Putting the pieces together
    11. Building the pieces
      1. Let’s check out the BeatModelInterface before looking at the implementation
      2. Now let’s have a look at the concrete BeatModel class
    12. The View
    13. Implementing the View
    14. Now for the Controller
      1. And here’s the implementation of the controller
    15. Putting it all together...
      1. And now for a test run...
      2. Things to do
    16. Exploring Strategy
    17. Adapting the Model
    18. Now we’re ready for a HeartController
      1. And that’s it! Now it’s time for some test code...
    19. And now for a test run...
      1. Things to do
    20. MVC and the Web
    21. Model 2: DJ’ing from a cell phone
      1. The plan
      2. Step one: the model
      3. Step two: the controller servlet
    22. Now we need a view...
    23. Putting Model 2 to the test...
      1. Things to do
    24. Design Patterns and Model 2
    25. Tools for your Design Toolbox
    26. Exercise Solutions
  22. 13. Better Living with Patterns: Patterns in the Real World
    1. Design Pattern defined
    2. Looking more closely at the Design Pattern definition
    3. So you wanna be a Design Patterns writer
    4. Organizing Design Patterns
    5. Thinking in Patterns
      1. Keep it simple (KISS)
      2. Design Patterns aren’t a magic bullet; in fact they’re not even a bullet!
      3. You know you need a pattern when...
      4. Refactoring time is Patterns time!
      5. Take out what you don’t really need. Don’t be afraid to remove a Design Pattern from your design
      6. If you don’t need it now, don’t do it now
    6. Your Mind on Patterns
    7. Don’t forget the power of the shared vocabulary
    8. Cruisin’ Objectville with the Gang of Four
    9. Your journey has just begun...
    10. The Patterns Zoo
    11. Annihilating evil with Anti-Patterns
    12. Tools for your Design Toolbox
    13. Leaving Objectville...
    14. Boy, it’s been great having you in Objectville
    15. Exercise Solutions
  23. A. Appendix: Leftover Patterns
    1. Bridge
    2. Why use the Bridge Pattern?
    3. Builder
    4. Why use the Builder Pattern?
    5. Chain of Responsibility
    6. How to use the Chain of Responsibility Pattern
    7. Flyweight
    8. Why use the Flyweight Pattern?
    9. Interpreter
    10. How to implement an interpreter
    11. Mediator
    12. Mediator in action...
    13. Memento
    14. The Memento at work
    15. Prototype
    16. Prototype to the rescue
    17. Visitor
    18. The Visitor drops by
  24. B.
  25. C. Mighty Gumball
  26. Index
  27. About the Authors
  28. Colophon
  29. Copyright

Chapter 1. Intro to Design Patterns: Welcome to Design Patterns

image with no caption

Someone has already solved your problems. In this chapter, you’ll learn why (and how) you can exploit the wisdom and lessons learned by other developers who’ve been down the same design problem road and survived the trip. Before we’re done, we’ll look at the use and benefits of design patterns, look at some key OO design principles, and walk through an example of how one pattern works. The best way to use patterns is to load your brain with them and then recognize places in your designs and existing applications where you can apply them. Instead of code reuse, with patterns you get experience reuse.

It started with a simple SimUDuck app

Joe works for a company that makes a highly successful duck pond simulation game, SimUDuck. The game can show a large variety of duck species swimming and making quacking sounds. The initial designers of the system used standard OO techniques and created one Duck superclass from which all other duck types inherit.

image with no caption

In the last year, the company has been under increasing pressure from competitors. After a week long off-site brainstorming session over golf, the company executives think it’s time for a big innovation. They need something really impressive to show at the upcoming shareholders meeting in Maui next week.

But now we need the ducks to FLY

The executives decided that flying ducks is just what the simulator needs to blow away the other duck sim competitors. And of course Joe’s manager told them it’ll be no problem for Joe to just whip something up in a week. “After all”, said Joe’s boss, “he’s an OO programmer... how hard can it be?”

image with no caption
image with no caption
image with no caption

But something went horribly wrong...

image with no caption
image with no caption

What happened?

Joe failed to notice that not all subclasses of Duck should fly. When Joe added new behavior to the Duck superclass, he was also adding behavior that was not appropriate for some Duck subclasses. He now has flying inanimate objects in the SimUDuck program.

A localized update to the code caused a nonlocal side effect (flying rubber ducks)!

image with no caption
image with no caption

What he thought was a great use of inheritance for the purpose of reuse hasn’t turned out so well when it comes to maintenance.

Joe thinks about inheritance...

image with no caption
image with no caption


Here’s another class in the hierarchy; notice that like RubberDuck, it doesn’t fly, but it also doesn’t quack.

How about an interface?

Joe realized that inheritance probably wasn’t the answer, because he just got a memo that says that the executives now want to update the product every six months (in ways they haven’t yet decided on). Joe knows the spec will keep changing and he’ll be forced to look at and possibly override fly() and quack() for every new Duck subclass that’s ever added to the program... forever.

So, he needs a cleaner way to have only some (but not all) of the duck types fly or quack.

image with no caption
image with no caption

What do YOU think about this design?

What would you do if you were Joe?

We know that not all of the subclasses should have flying or quacking behavior, so inheritance isn’t the right answer. But while having the subclasses implement Flyable and/or Quackable solves part of the problem (no inappropriately flying rubber ducks), it completely destroys code reuse for those behaviors, so it just creates a different maintenance nightmare. And of course there might be more than one kind of flying behavior even among the ducks that do fly...

image with no caption

At this point you might be waiting for a Design Pattern to come riding in on a white horse and save the day. But what fun would that be? No, we’re going to figure out a solution the old-fashioned way – by applying good OO software design principles.

image with no caption

The one constant in software development

Okay, what’s the one thing you can always count on in software development?

No matter where you work, what you’re building, or what language you are programming in, what’s the one true constant that will be with you always?

image with no caption

(use a mirror to see the answer)

No matter how well you design an application, over time an application must grow and change or it will die.

Zeroing in on the problem...

So we know using inheritance hasn’t worked out very well, since the duck behavior keeps changing across the subclasses, and it’s not appropriate for all subclasses to have those behaviors. The Flyable and Quackable interface sounded promising at first – only ducks that really do fly will be Flyable, etc – except Java interfaces have no implementation code, so no code reuse. And that means that whenever you need to modify a behavior, you’re forced to track down and change it in all the different subclasses where that behavior is defined, probably introducing new bugs along the way!

Luckily, there’s a design principle for just this situation.


Design Principle

Identify the aspects of your application that vary and separate them from what stays the same.


The first of many design principles. We’ll spend more time on these throughout the book.

Take what varies and “encapsulate” it so it won’t affect the rest of your code.

The result? Fewer unintended consequences from code changes and more flexibility in your systems!

In other words, if you’ve got some aspect of your code that is changing, say with every new requirement, then you know you’ve got a behavior that needs to be pulled out and separated from all the stuff that doesn’t change.

Here’s another way to think about this principle: take the parts that vary and encapsulate them, so that later you can alter or extend the parts that vary without affecting those that don’t.

As simple as this concept is, it forms the basis for almost every design pattern. All patterns provide a way to let some part of a system vary independently of all other parts.

Okay, time to pull the duck behavior out of the Duck classes!

Separating what changes from what stays the same

Where do we start? As far as we can tell, other than the problems with fly() and quack(), the Duck class is working well and there are no other parts of it that appear to vary or change frequently. So, other than a few slight changes, we’re going to pretty much leave the Duck class alone.

Now, to separate the “parts that change from those that stay the same”, we are going to create two sets of classes (totally apart from Duck), one for fly and one for quack. Each set of classes will hold all the implementations of their respective behavior. For instance, we might have one class that implements quacking, another that implements squeaking, and another that implements silence.

  • We know that fly() and quack() are the parts of the Duck class that vary across ducks.

  • To separate these behaviors from the Duck class, we’ll pull both methods out of the Duck class and create a new set of classes to represent each behavior.

image with no caption

Designing the Duck Behaviors

So how are we going to design the set of classes that implement the fly and quack behaviors?

We’d like to keep things flexible; after all, it was the inflexibility in the duck behaviors that got us into trouble in the first place. And we know that we want to assign behaviors to the instances of Duck. For example, we might want to instantiate a new MallardDuck instance and initialize it with a specific type of flying behavior. And while we’re there, why not make sure that we can change the behavior of a duck dynamically? In other words, we should include behavior setter methods in the Duck classes so that we can change the MallardDuck’s flying behavior at runtime.

Given these goals, let’s look at our second design principle:


Design Principle

Program to an interface, not an implementation.

We’ll use an interface to represent each behavior – for instance, FlyBehavior and QuackBehavior – and each implementation of a behavior will implement one of those interfaces.

From now on, the Duck behaviors will live in a separate class—a class that implements a particular behavior interface.

That way, the Duck classes won’t need to know any of the implementation details for their own behaviors.

So this time it won’t be the Duck classes that will implement the flying and quacking interfaces. Instead, we’ll make a set of classes whose entire reason for living is to represent a behavior (for example, “squeaking”), and it’s the behavior class, rather than the Duck class, that will implement the behavior interface.

This is in contrast to the way we were doing things before, where a behavior either came from a concrete implementation in the superclass Duck, or by providing a specialized implementation in the subclass itself. In both cases we were relying on an implementation. We were locked into using that specific implementation and there was no room for changing the behavior (other than writing more code).

image with no caption

With our new design, the Duck subclasses will use a behavior represented by an interface (FlyBehavior and QuackBehavior), so that the actual implementation of the behavior (in other words, the specific concrete behavior coded in the class that implements the FlyBehavior or QuackBehavior) won’t be locked into the Duck subclass.

image with no caption

“Program to an interface” really means “Program to a supertype.

The word interface is overloaded here. There’s the concept of interface, but there’s also the Java construct interface. You can program to an interface, without having to actually use a Java interface. The point is to exploit polymorphism by programming to a supertype so that the actual runtime object isn’t locked into the code. And we could rephrase “program to a supertype” as “the declared type of the variables should be a supertype, usually an abstract class or interface, so that the objects assigned to those variables can be of any concrete implementation of the supertype, which means the class declaring them doesn’t have to know about the actual object types!”

This is probably old news to you, but just to make sure we’re all saying the same thing, here’s a simple example of using a polymorphic type – imagine an abstract class Animal, with two concrete implementations, Dog and Cat.

Programming to an implementation would be:

Dog d = new Dog();


Declaring the variable “d” as type Dog (a concrete implementation of Animal) forces us to code to a concrete implementation.

But programming to an interface/supertype would be:

Animal animal = new Dog();


We know it’s a Dog, but we can now use the animal reference polymorphically.

Even better, rather than hard-coding the instantiation of the subtype (like new Dog()) into the code, assign the concrete implementation object at runtime:

a = getAnimal();


We don’t know WHAT the actual animal subtype is... all we care about is that it knows how to respond to makeSound().

image with no caption

Implementing the Duck Behaviors

Here we have the two interfaces, FlyBehavior and QuackBehavior along with the corresponding classes that implement each concrete behavior:

image with no caption
image with no caption


So we get the benefit of REUSE without all the baggage that comes along with inheritance.


1) Create a FlyRocketPowered class that implements the FlyBehavior interface.

2) One example, a duck call (a device that makes duck sounds).

Integrating the Duck Behavior

The key is that a Duck will now delegate its flying and quacking behavior, instead of using quacking and flying methods defined in the Duck class (or subclass).

Here’s how:

  1. First we’ll add two instance variables to the Duck class called flyBehavior and quackBehavior, that are declared as the interface type (not a concrete class implementation type). Each duck object will set these variables polymorphically to reference the specific behavior type it would like at runtime (FlyWithWings, Squeak, etc.).

    We’ll also remove the fly() and quack() methods from the Duck class (and any subclasses) because we’ve moved this behavior out into the FlyBehavior and QuackBehavior classes.

    We’ll replace fly() and quack() in the Duck class with two similar methods, called performFly() and performQuack(); you’ll see how they work next.

    image with no caption
  2. Now we implement performQuack():

    image with no caption

    Pretty simple, huh? To perform the quack, a Duck just allows the object that is referenced by quackBehavior to quack for it.

    In this part of the code we don’t care what kind of object it is, all we care about is that it knows how to quack()!

More Integration...

  1. Okay, time to worry about how the flyBehavior and quackBehavior instance variables are set. Let’s take a look at the MallardDuck class:

    image with no caption

    So MallardDuck’s quack is a real live duck quack, not a squeak and not a mute quack. So what happens here? When a MallardDuck is instantiated, its constructor initializes the MallardDuck’s inherited quackBehavior instance variable to a new instance of type Quack (a QuackBehavior concrete implementation class).

    And the same is true for the duck’s flying behavior – the MallardDuck’s constructor initializes the flyBehavior instance variable with an instance of type FlyWithWings (a FlyBehavior concrete implementation class).

image with no caption

Good catch, that’s exactly what we’re doing... for now.

Later in the book we’ll have more patterns in our toolbox that can help us fix it.

Still, notice that while we are setting the behaviors to concrete classes (by instantiating a behavior class like Quack or FlyWithWings and assigning it to our behavior reference variable), we could easily change that at runtime.

So, we still have a lot of flexibility here, but we’re doing a poor job of initializing the instance variables in a flexible way. But think about it, since the quackBehavior instance variable is an interface type, we could (through the magic of polymorphism) dynamically assign a different QuackBehavior implementation class at runtime.

Take a moment and think about how you would implement a duck so that its behavior could change at runtime. (You’ll see the code that does this a few pages from now.)

Testing the Duck code

  1. Type and compile the Duck class below (, and the MallardDuck class from two pages back (

    image with no caption
  2. Type and compile the FlyBehavior interface ( and the two behavior implementation classes ( and

    image with no caption
  3. Type and compile the QuackBehavior interface ( and the three behavior implementation classes (,, and

    public interface QuackBehavior {
       public void quack();
    public class Quack implements QuackBehavior {
       public void quack() {
    public class MuteQuack implements QuackBehavior {
       public void quack() {
           System.out.println("<< Silence >>");
    public class Squeak implements QuackBehavior {
       public void quack() {
  4. Type and compile the test class (

    image with no caption
  5. Run the code!

    image with no caption

Setting behavior dynamically

What a shame to have all this dynamic talent built into our ducks and not be using it! Imagine you want to set the duck’s behavior type through a setter method on the duck subclass, rather than by instantiating it in the duck’s constructor.

  1. Add two new methods to the Duck class:

    image with no caption
  2. Make a new Duck type (

    image with no caption
  3. Make a new FlyBehavior type (

    image with no caption
  4. Change the test class (, add the ModelDuck, and make the ModelDuck rocket-enabled.

    image with no caption

To change a duck’s behavior at runtime, just call the duck’s setter method for that behavior.

The Big Picture on encapsulated behaviors

Okay, now that we’ve done the deep dive on the duck simulator design, it’s time to come back up for air and take a look at the big picture.

Below is the entire reworked class structure. We have everything you’d expect: ducks extending Duck, fly behaviors implementing FlyBehavior and quack behaviors implementing QuackBehavior.

Notice also that we’ve started to describe things a little differently. Instead of thinking of the duck behaviors as a set of behaviors, we’ll start thinking of them as a family of algorithms. Think about it: in the SimUDuck design, the algorithms represent things a duck would do (different ways of quacking or flying), but we could just as easily use the same techniques for a set of classes that implement the ways to compute state sales tax by different states.

Pay careful attention to the relationships between the classes. In fact, grab your pen and write the appropriate relationship (IS-A, HAS-A and IMPLEMENTS) on each arrow in the class diagram.

image with no caption

HAS-A can be better than IS-A

The HAS-A relationship is an interesting one: each duck has a FlyBehavior and a QuackBehavior to which it delegates flying and quacking.

When you put two classes together like this you’re using composition. Instead of inheriting their behavior, the ducks get their behavior by being composed with the right behavior object.

This is an important technique; in fact, we’ve been using our third design principle:


Design Principle

Favor composition over inheritance.

As you’ve seen, creating systems using composition gives you a lot more flexibility. Not only does it let you encapsulate a family of algorithms into their own set of classes, but it also lets you change behavior at runtime as long as the object you’re composing with implements the correct behavior interface.

Composition is used in many design patterns and you’ll see a lot more about its advantages and disadvantages throughout the book.

Brain Power

A duck call is a device that hunters use to mimic the calls (quacks) of ducks. How would you implement your own duck call that does not inherit from the Duck class?

Speaking of Design Patterns...

Overheard at the local diner...

image with no caption

What’s the difference between these two orders? Not a thing! They’re both the same order, except Alice is using twice the number of words and trying the patience of a grumpy short order cook.

What’s Flo got that Alice doesn’t? A shared vocabulary with the short order cook. Not only is it easier to communicate with the cook, but it gives the cook less to remember because he’s got all the diner patterns in his head.

Design Patterns give you a shared vocabulary with other developers. Once you’ve got the vocabulary you can more easily communicate with other developers and inspire those who don’t know patterns to start learning them. It also elevates your thinking about architectures by letting you think at the pattern level, not the nitty gritty object level.

Overheard in the next cubicle...

image with no caption

Brain Power

Can you think of other shared vocabularies that are used beyond OO design and diner talk? (Hint: how about auto mechanics, carpenters, gourmet chefs, air traffic control). What qualities are communicated along with the lingo?

Can you think of aspects of OO design that get communicated along with pattern names? What qualities get communicated along with the name “Strategy Pattern”?

image with no caption

The power of a shared pattern vocabulary

When you communicate using patterns you are doing more than just sharing LINGO.

Shared pattern vocabularies are POWERFUL. When you communicate with another developer or your team using patterns, you are communicating not just a pattern name but a whole set of qualities, characteristics and constraints that the pattern represents.


“We’re using the strategy pattern to implement the various behaviors of our ducks.” This tells you the duck behavior has been encapsulated into its own set of classes that can be easily expanded and changed, even at runtime if needed.

Patterns allow you to say more with less. When you use a pattern in a description, other developers quickly know precisely the design you have in mind.

Talking at the pattern level allows you to stay “in the design” longer. Talking about software systems using patterns allows you to keep the discussion at the design level, without having to dive down to the nitty gritty details of implementing objects and classes.


How many design meetings have you been in that quickly degrade into implementation details?

Shared vocabularies can turbo charge your development team. A team well versed in design patterns can move more quickly with less room for misunderstanding.


As your team begins to share design ideas and experience in terms of patterns, you will build a community of patterns users.

Shared vocabularies encourage more junior developers to get up to speed. Junior developers look up to experienced developers. When senior developers make use of design patterns, junior developers also become motivated to learn them. Build a community of pattern users at your organization.


Think about starting a patterns study group at your organization, maybe you can even get paid while you’re learning...

How do I use Design Patterns?

We’ve all used off-the-shelf libraries and frameworks. We take them, write some code against their APIs, compile them into our programs, and benefit from a lot of code someone else has written. Think about the Java APIs and all the functionality they give you: network, GUI, IO, etc. Libraries and frameworks go a long way towards a development model where we can just pick and choose components and plug them right in. But... they don’t help us structure our own applications in ways that are easier to understand, more maintainable and flexible. That’s where Design Patterns come in.

Design patterns don’t go directly into your code, they first go into your BRAIN. Once you’ve loaded your brain with a good working knowledge of patterns, you can then start to apply them to your new designs, and rework your old code when you find it’s degrading into an inflexible mess of jungle spaghetti code.

image with no caption
image with no caption

Skeptical Developer

image with no caption

Friendly Patterns Guru

Developer: Okay, hmm, but isn’t this all just good object-oriented design; I mean as long as I follow encapsulation and I know about abstraction, inheritance, and polymorphism, do I really need to think about Design Patterns? Isn’t it pretty straightforward? Isn’t this why I took all those OO courses? I think Design Patterns are useful for people who don’t know good OO design.

Guru: Ah, this is one of the true misunderstandings of object-oriented development: that by knowing the OO basics we are automatically going to be good at building flexible, reusable, and maintainable systems.

Developer: No?

Guru: No. As it turns out, constructing OO systems that have these properties is not always obvious and has been discovered only through hard work.

Developer: I think I’m starting to get it. These, sometimes non-obvious, ways of constructing object-oriented systems have been collected...

Guru: ...yes, into a set of patterns called Design Patterns.

Developer: So, by knowing patterns, I can skip the hard work and jump straight to designs that always work?

Guru: Yes, to an extent, but remember, design is an art. There will always be tradeoffs. But, if you follow well thought-out and time-tested design patterns, you’ll be way ahead.

Developer: What do I do if I can’t find a pattern?

image with no caption

Guru: There are some object oriented-principles that underlie the patterns, and knowing these will help you to cope when you can’t find a pattern that matches your problem.

Developer: Principles? You mean beyond abstraction, encapsulation, and...

Guru: Yes, one of the secrets to creating maintainable OO systems is thinking about how they might change in the future and these principles address those issues.

Tools for your Design Toolbox

You’ve nearly made it through the first chapter! You’ve already put a few tools in your OO toolbox; let’s make a list of them before we move on to Chapter 2.

image with no caption


image with no caption

The best content for your career. Discover unlimited learning on demand for around $1/day.