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
O'Reilly logo

How to Use This Book: Intro

image with no caption

In this section, we answer the burning question: “So, why DID they put that in a design patterns book?”

Who is this book for?

If you can answer “yes” to all of these:

  1. Do you know Java? (You don’t need to be a guru.)


    You’ll probably be okay if you know C# instead.

  2. Do you want to learn, understand, remember, and apply design patterns, including the OO design principles upon which design patterns are based?

  3. Do you prefer stimulating dinner party conversation to dry, dull, academic lectures?

this book is for you.

Who should probably back away from this book?

If you can answer “yes” to any one of these:

  1. Are you completely new to Java?

    (You don’t need to be advanced, and even if you don’t know Java, but you know C#, you’ll probably understand at least 80% of the code examples. You also might be okay with just a C++ background.)

  2. Are you a kick-butt OO designer/developer looking for a reference book?

  3. Are you an architect looking for enterprise design patterns?

  4. Are you afraid to try something different? Would you rather have a root canal than mix stripes with plaid? Do you believe that a technical book can’t be serious if Java components are anthropomorphized?

this book is not for you.

image with no caption

[note from marketing: this book is for anyone with a credit card.]

We know what you’re thinking

“How can this be a serious programming book?”

“What’s with all the graphics?”

“Can I actually learn it this way?”

And we know what your brain is thinking

Your brain craves novelty. It’s always searching, scanning, waiting for something unusual. It was built that way, and it helps you stay alive.

Today, you’re less likely to be a tiger snack. But your brain’s still looking. You just never know.

So what does your brain do with all the routine, ordinary, normal things you encounter? Everything it can to stop them from interfering with the brain’s real job—recording things that matter. It doesn’t bother saving the boring things; they never make it past the “this is obviously not important” filter.

image with no caption

How does your brain know what’s important? Suppose you’re out for a day hike and a tiger jumps in front of you, what happens inside your head and body?

Neurons fire. Emotions crank up. Chemicals surge.

And that’s how your brain knows...

This must be important! Don’t forget it!

But imagine you’re at home, or in a library. It’s a safe, warm, tiger-free zone. You’re studying. Getting ready for an exam. Or trying to learn some tough technical topic your boss thinks will take a week, ten days at the most.

Just one problem. Your brain’s trying to do you a big favor. It’s trying to make sure that this obviously non-important content doesn’t clutter up scarce resources. Resources that are better spent storing the really big things. Like tigers. Like the danger of fire. Like how you should never again snowboard in shorts.

And there’s no simple way to tell your brain, “Hey brain, thank you very much, but no matter how dull this book is, and how little I’m registering on the emotional Richter scale right now, I really do want you to keep this stuff around.”

image with no caption

Metacognition: thinking about thinking

If you really want to learn, and you want to learn more quickly and more deeply, pay attention to how you pay attention. Think about how you think. Learn how you learn.

Most of us did not take courses on metacognition or learning theory when we were growing up. We were expected to learn, but rarely taught to learn.

But we assume that if you’re holding this book, you really want to learn design patterns. And you probably don’t want to spend a lot of time. And you want to remember what you read, and be able to apply it. And for that, you’ve got to understand it. To get the most from this book, or any book or learning experience, take responsibility for your brain. Your brain on this content.

The trick is to get your brain to see the new material you’re learning as Really Important. Crucial to your well-being. As important as a tiger. Otherwise, you’re in for a constant battle, with your brain doing its best to keep the new content from sticking.

image with no caption

So how DO you get your brain to think Design Patterns are as important as a tiger?

There’s the slow, tedious way, or the faster, more effective way. The slow way is about sheer repetition. You obviously know that you are able to learn and remember even the dullest of topics, if you keep pounding on the same thing. With enough repetition, your brain says, “This doesn’t feel important to him, but he keeps looking at the same thing over and over and over, so I suppose it must be.”

The faster way is to do anything that increases brain activity, especially different types of brain activity. The things on the previous page are a big part of the solution, and they’re all things that have been proven to help your brain work in your favor. For example, studies show that putting words within the pictures they describe (as opposed to somewhere else in the page, like a caption or in the body text) causes your brain to try to makes sense of how the words and picture relate, and this causes more neurons to fire. More neurons firing = more chances for your brain to get that this is something worth paying attention to, and possibly recording.

A conversational style helps because people tend to pay more attention when they perceive that they’re in a conversation, since they’re expected to follow along and hold up their end. The amazing thing is, your brain doesn’t necessarily care that the “conversation” is between you and a book! On the other hand, if the writing style is formal and dry, your brain perceives it the same way you experience being lectured to while sitting in a roomful of passive attendees. No need to stay awake.

But pictures and conversational style are just the beginning.

Here’s what WE did

We used pictures, because your brain is tuned for visuals, not text. As far as your brain’s concerned, a picture really is worth 1024 words. And when text and pictures work together, we embedded the text in the pictures because your brain works more effectively when the text is within the thing the text refers to, as opposed to in a caption or buried in the text somewhere.

image with no caption

We used redundancy, saying the same thing in different ways and with different media types, and multiple senses, to increase the chance that the content gets coded into more than one area of your brain.

We used concepts and pictures in unexpected ways because your brain is tuned for novelty, and we used pictures and ideas with at least some emotional content, because your brain is tuned to pay attention to the biochemistry of emotions. That which causes you to feel something is more likely to be remembered, even if that feeling is nothing more than a little humor, surprise, or interest.

image with no caption

The Patterns Guru

We used a personalized, conversational style, because your brain is tuned to pay more attention when it believes you’re in a conversation than if it thinks you’re passively listening to a presentation. Your brain does this even when you’re reading.

We included more than 40 activities, because your brain is tuned to learn and remember more when you do things than when you read about things. And we made the exercises challenging-yet-do-able, because that’s what most people prefer.

We used multiple learning styles, because you might prefer step-by-step procedures, while someone else wants to understand the big picture first, while someone else just wants to see a code example. But regardless of your own learning preference, everyone benefits from seeing the same content represented in multiple ways.

image with no caption


We include content for both sides of your brain, because the more of your brain you engage, the more likely you are to learn and remember, and the longer you can stay focused. Since working one side of the brain often means giving the other side a chance to rest, you can be more productive at learning for a longer period of time.

image with no caption


And we included stories and exercises that present more than one point of view, because your brain is tuned to learn more deeply when it’s forced to make evaluations and judgements.

We included challenges, with exercises, and by asking questions that don’t always have a straight answer, because your brain is tuned to learn and remember when it has to work at something. Think about it—you can’t get your body in shape just by watching people at the gym. But we did our best to make sure that when you’re working hard, it’s on the right things. That you’re not spending one extra dendrite processing a hard-to-understand example, or parsing difficult, jargon-laden, or overly terse text.

We used people. In stories, examples, pictures, etc., because, well, because you’re a person. And your brain pays more attention to people than it does to things.

image with no caption

We used an 80/20 approach. We assume that if you’re going for a PhD in software design, this won’t be your only book. So we don’t talk about everything. Just the stuff you’ll actually need.

Here’s what YOU can do to bend your brain into submission

image with no caption

cut this out and stick it on your refrigerator.

So, we did our part. The rest is up to you. These tips are a starting point; listen to your brain and figure out what works for you and what doesn’t. Try new things.

  1. Slow down. The more you understand, the less you have to memorize.

    Don’t just read. Stop and think. When the book asks you a question, don’t just skip to the answer. Imagine that someone really is asking the question. The more deeply you force your brain to think, the better chance you have of learning and remembering.

  2. Do the exercises. Write your own notes.

    We put them in, but if we did them for you, that would be like having someone else do your workouts for you. And don’t just look at the exercises. Use a pencil. There’s plenty of evidence that physical activity while learning can increase the learning.

  3. Read the “There are No Dumb Questions”

    That means all of them. They’re not optional side-bars—they’re part of the core content! Don’t skip them.

  4. Make this the last thing you read before bed. Or at least the last challenging thing.

    Part of the learning (especially the transfer to long-term memory) happens after you put the book down. Your brain needs time on its own, to do more processing. If you put in something new during that processing-time, some of what you just learned will be lost.

  5. Drink water. Lots of it.

    Your brain works best in a nice bath of fluid. Dehydration (which can happen before you ever feel thirsty) decreases cognitive function.

  6. Talk about it. Out loud.

    Speaking activates a different part of the brain. If you’re trying to understand something, or increase your chance of remembering it later, say it out loud. Better still, try to explain it out loud to someone else. You’ll learn more quickly, and you might uncover ideas you hadn’t known were there when you were reading about it.

  7. Listen to your brain.

    Pay attention to whether your brain is getting overloaded. If you find yourself starting to skim the surface or forget what you just read, it’s time for a break. Once you go past a certain point, you won’t learn faster by trying to shove more in, and you might even hurt the process.

  8. Feel something!

    Your brain needs to know that this matters. Get involved with the stories. Make up your own captions for the photos. Groaning over a bad joke is still better than feeling nothing at all.

  9. Design something!

    Apply this to something new you’re designing, or refactor an older project. Just do something to get some experience beyond the exercises and activities in this book. All you need is a pencil and a problem to solve... a problem that might benefit from one or more design patterns.

Read Me

This is a learning experience, not a reference book. We deliberately stripped out everything that might get in the way of learning whatever it is we’re working on at that point in the book. And the first time through, you need to begin at the beginning, because the book makes assumptions about what you’ve already seen and learned.

image with no caption

We use simple UML-like diagrams.

Although there’s a good chance you’ve run across UML, it’s not covered in the book, and it’s not a prerequisite for the book. If you’ve never seen UML before, don’t worry, we’ll give you a few pointers along the way. So in other words, you won’t have to worry about Design Patterns and UML at the same time. Our diagrams are “UML-like” -- while we try to be true to UML there are times we bend the rules a bit, usually for our own selfish artistic reasons.

We don’t cover every single Design Pattern ever created.

There are a lot of Design Patterns: The original foundational patterns (known as the GoF patterns), Sun’s J2EE patterns, JSP patterns, architectural patterns, game design patterns and a lot more. But our goal was to make sure the book weighed less than the person reading it, so we don’t cover them all here. Our focus is on the core patterns that matter from the original GoF patterns, and making sure that you really, truly, deeply understand how and when to use them. You will find a brief look at some of the other patterns (the ones you’re far less likely to use) in the appendix. In any case, once you’re done with Head First Design Patterns, you’ll be able to pick up any pattern catalog and get up to speed quickly.

The activities are NOT optional.

The exercises and activities are not add-ons; they’re part of the core content of the book. Some of them are to help with memory, some for understanding, and some to help you apply what you’ve learned. Don’t skip the exercises. The crossword puzzles are the only things you don’t have to do, but they’re good for giving your brain a chance to think about the words from a different context.

We use the word “composition” in the general OO sense, which is more flexible than the strict UML use of “composition”.

When we say “one object is composed with another object” we mean that they are related by a HAS-A relationship. Our use reflects the traditional use of the term and is the one used in the GoF text (you’ll learn what that is later). More recently, UML has refined this term into several types of composition. If you are an UML expert, you’ll still be able to read the book and you should be able to easily map the use of composition to more refined terms as you read.

The redundancy is intentional and important.

One distinct difference in a Head First book is that we want you to really get it. And we want you to finish the book remembering what you’ve learned. Most reference books don’t have retention and recall as a goal, but this book is about learning, so you’ll see some of the same concepts come up more than once.

The code examples are as lean as possible.

Our readers tell us that it’s frustrating to wade through 200 lines of code looking for the two lines they need to understand. Most examples in this book are shown within the smallest possible context, so that the part you’re trying to learn is clear and simple. Don’t expect all of the code to be robust, or even complete—the examples are written specifically for learning, and aren’t always fully-functional.

In some cases, we haven’t included all of the import statements needed, but we assume that if you’re a Java programmer, you know that ArrayList is in java.util, for example. If the imports were not part of the normal core J2SE API, we mention it. We’ve also placed all the source code on the web so you can download it. You’ll find it at

Also, for the sake of focusing on the learning side of the code, we did not put our classes into packages (in other words, they’re all in the Java default package). We don’t recommend this in the real world, and when you download the code examples from this book, you’ll find that all classes are in packages.

The ‘Brain Power’ exercises don’t have answers.

For some of them, there is no right answer, and for others, part of the learning experience of the Brain Power activities is for you to decide if and when your answers are right. In some of the Brain Power exercises you will find hints to point you in the right direction.

Tech Reviewers

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

In memory of Philippe Maquet


image with no caption

Your amazing technical expertise, relentless enthusiasm, and deep concern for the learner will inspire us always.

We will never forget you.


At O’Reilly:

Our biggest thanks to Mike Loukides at O’Reilly, for starting it all, and helping to shape the Head First concept into a series. And a big thanks to the driving force behind Head First, Tim O’Reilly. Thanks to the clever Head First “series mom” Kyle Hart, to rock and roll star Ellie Volkhausen for her inspired cover design and also to Colleen Gorman for her hardcore copyedit. Finally, thanks to Mike Hendrickson for championing this Design Patterns book, and building the team.

Our intrepid reviewers:

We are extremely grateful for our technical review director Johannes deJong. You are our hero, Johannes. And we deeply appreciate the contributions of the co-manager of the Javaranch review team, the late Philippe Maquet. You have single-handedly brightened the lives of thousands of developers, and the impact you’ve had on their (and our) lives is forever.

Jef Cumps is scarily good at finding problems in our draft chapters, and once again made a huge difference for the book. Thanks Jef! Valentin Cretazz (AOP guy), who has been with us from the very first Head First book, proved (as always) just how much we really need his technical expertise and insight. You rock Valentin (but lose the tie).

Two newcomers to the HF review team, Barney Marispini and Ike Van Atta did a kick butt job on the book—you guys gave us some really crucial feedback. Thanks for joining the team.

We also got some excellent technical help from Javaranch moderators/gurus Mark Spritzler, Jason Menard, Dirk Schreckmann, Thomas Paul, and Margarita Isaeva. And as always, thanks especially to the Trail Boss, Paul Wheaton.

Thanks to the finalists of the Javaranch “Pick the Head First Design Patterns Cover” contest. The winner, Si Brewster, submitted the winning essay that persuaded us to pick the woman you see on our cover. Other finalists include Andrew Esse, Gian Franco Casula, Helen Crosbie, Pho Tek, Helen Thomas, Sateesh Kommineni, and Jeff Fisher.

Even more people[1]

From Eric and Elisabeth

Writing a Head First book is a wild ride with two amazing tour guides: Kathy Sierra and Bert Bates. With Kathy and Bert you throw out all book writing convention and enter a world full of storytelling, learning theory, cognitive science, and pop culture, where the reader always rules. Thanks to both of you for letting us enter your amazing world; we hope we’ve done Head First justice. Seriously, this has been amazing. Thanks for all your careful guidance, for pushing us to go forward and most of all, for trusting us (with your baby). You’re both certainly “wickedly smart” and you’re also the hippest 29 year olds we know. So... what’s next?

A big thank you to Mike Loukides and Mike Hendrickson. Mike L. was with us every step of the way. Mike, your insightful feedback helped shape the book and your encouragement kept us moving ahead. Mike H., thanks for your persistence over five years in trying to get us to write a patterns book; we finally did it and we’re glad we waited for Head First.

A very special thanks to Erich Gamma, who went far beyond the call of duty in reviewing this book (he even took a draft with him on vacation). Erich, your interest in this book inspired us and your thorough technical review improved it immeasurably. Thanks as well to the entire Gang of Four for their support & interest, and for making a special appearance in Objectville. We are also indebted to Ward Cunningham and the patterns community who created the Portland Pattern Repository – an indespensible resource for us in writing this book.

It takes a village to write a technical book: Bill Pugh and Ken Arnold gave us expert advice on Singleton. Joshua Marinacci provided rockin’ Swing tips and advice. John Brewer’s “Why a Duck?” paper inspired SimUDuck (and we’re glad he likes ducks too). Dan Friedman inspired the Little Singleton example. Daniel Steinberg acted as our “technical liason” and our emotional support network. And thanks to Apple’s James Dempsey for allowing us to use his MVC song.

Last, a personal thank you to the Javaranch review team for their top-notch reviews and warm support. There’s more of you in this book than you know.

From Kathy and Bert

We’d like to thank Mike Hendrickson for finding Eric and Elisabeth... but we can’t. Because of these two, we discovered (to our horror) that we aren’t the only ones who can do a Head First book.;) However, if readers want to believe that it’s really Kathy and Bert who did the cool things in the book, well, who are we to set them straight?

[1] The large number of acknowledgments is because we’re testing the theory that everyone mentioned in a book acknowledgment will buy at least one copy, probably more, what with relatives and everything. If you’d like to be in the acknowledgment of our next book, and you have a large family, write to us.

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