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 4. The Factory Pattern: Baking with OO Goodness

image with no caption

Get ready to bake some loosely coupled OO designs. There is more to making objects than just using the new operator. You’ll learn that instantiation is an activity that shouldn’t always be done in public and can often lead to coupling problems. And you don’t want that, do you? Find out how Factory Patterns can help save you from embarrassing dependencies.

image with no caption

When you see “new”, think “concrete”.

Yes, when you use new you are certainly instantiating a concrete class, so that’s definitely an implementation, not an interface. And it’s a good question; you’ve learned that tying your code to a concrete class can make it more fragile and less flexible.

image with no caption

When you have a whole set of related concrete classes, often you’re forced to write code like this:

image with no caption

Here we’ve got several concrete classes being instantiated, and the decision of which to instantiate is made at runtime depending on some set of conditions.

When you see code like this, you know that when it comes time for changes or extensions, you’ll have to reopen this code and examine what needs to be added (or deleted). Often this kind of code ends up in several parts of the application making maintenance and updates more difficult and error-prone.

image with no caption

What’s wrong with “new”?

Technically there’s nothing wrong with new, after all, it’s a fundamental part of Java. The real culprit is our old friend CHANGE and how change impacts our use of new.

By coding to an interface, you know you can insulate yourself from a lot of changes that might happen to a system down the road. Why? If your code is written to an interface, then it will work with any new classes implementing that interface through polymorphism. However, when you have code that makes use of lots of concrete classes, you’re looking for trouble because that code may have to be changed as new concrete classes are added. So, in other words, your code will not be “closed for modification.” To extend it with new concrete types, you’ll have to reopen it.


Remember that designs should be “open for extension but closed for modification” - see Chapter 3 for a review.

So what can you do? It’s times like these that you can fall back on OO Design Principles to look for clues. Remember, our first principle deals with change and guides us to identify the aspects that vary and separate them from what stays the same.

Brain Power

How might you take all the parts of your application that instantiate concrete classes and separate or encapsulate them from the rest of your application?

Identifying the aspects that vary

image with no caption

Let’s say you have a pizza shop, and as a cutting-edge pizza store owner in Objectville you might end up writing some code like this:

image with no caption

But you need more than one type of pizza...

So then you’d add some code that determines the appropriate type of pizza and then goes about making the pizza:

image with no caption

But the pressure is on to add more pizza types

You realize that all of your competitors have added a couple of trendy pizzas to their menus: the Clam Pizza and the Veggie Pizza. Obviously you need to keep up with the competition, so you’ll add these items to your menu. And you haven’t been selling many Greek Pizzas lately, so you decide to take that off the menu:

image with no caption

Clearly, dealing with which concrete class is instantiated is really messing up our orderPizza() method and preventing it from being closed for modification. But now that we know what is varying and what isn’t, it’s probably time to encapsulate it.

Encapsulating object creation

So now we know we’d be better off moving the object creation out of the orderPizza() method. But how? Well, what we’re going to do is take the creation code and move it out into another object that is only going to be concerned with creating pizzas.

image with no caption

We’ve got a name for this new object: we call it a Factory.

Factories handle the details of object creation. Once we have a SimplePizzaFactory, our orderPizza() method just becomes a client of that object. Any time it needs a pizza it asks the pizza factory to make one. Gone are the days when the orderPizza() method needs to know about Greek versus Clam pizzas. Now the orderPizza() method just cares that it gets a pizza, which implements the Pizza interface so that it can call prepare(), bake(), cut(), and box().

We’ve still got a few details to fill in here; for instance, what does the orderPizza() method replace its creation code with? Let’s implement a simple factory for the pizza store and find out...

Building a simple pizza factory

We’ll start with the factory itself. What we’re going to do is define a class that encapsulates the object creation for all pizzas. Here it is...

image with no caption

Reworking the PizzaStore class

Now it’s time to fix up our client code. What we want to do is rely on the factory to create the pizzas for us. Here are the changes:

image with no caption

Brain Power


We know that object composition allows us to change behavior dynamically at runtime (among other things) because we can swap in and out implementations. How might we be able to use that in the PizzaStore? What factory implementations might we be able to swap in and out?


We don’t know about you, but we’re thinking New York, Chicago, and California style pizza factories (let’s not forget New Haven, too)

The Simple Factory defined

image with no caption

Pattern Honorable Mention

The Simple Factory isn’t actually a Design Pattern; it’s more of a programming idiom. But it is commonly used, so we’ll give it a Head First Pattern Honorable Mention. Some developers do mistake this idiom for the “Factory Pattern,” so the next time there is an awkward silence between you and another developer, you’ve got a nice topic to break the ice.

Just because Simple Factory isn’t a REAL pattern doesn’t mean we shouldn’t check out how it’s put together. Let’s take a look at the class diagram of our new Pizza Store:

image with no caption

*Just another reminder: in design patterns, the phrase “implement an interface” does NOT always mean “write a class that implements a Java interface, by using the “implements” keyword in the class declaration.” In the general use of the phrase, a concrete class implementing a method from a supertype (which could be a class OR interface) is still considered to be “implementing the interface” of that supertype.

Think of Simple Factory as a warm up. Next, we’ll explore two heavy duty patterns that are both factories. But don’t worry, there’s more pizza to come!

Franchising the pizza store

Your Objectville PizzaStore has done so well that you’ve trounced the competition and now everyone wants a PizzaStore in their own neighborhood. As the franchiser, you want to ensure the quality of the franchise operations and so you want them to use your time-tested code.

But what about regional differences? Each franchise might want to offer different styles of pizzas (New York, Chicago, and California, to name a few), depending on where the franchise store is located and the tastes of the local pizza connoisseurs.

image with no caption

We’ve seen one approach...

If we take out SimplePizzaFactory and create three different factories, NYPizzaFactory, ChicagoPizzaFactory and CaliforniaPizzaFactory, then we can just compose the PizzaStore with the appropriate factory and a franchise is good to go. That’s one approach.

Let’s see what that would look like...

image with no caption

But you’d like a little more quality control...

So you test marketed the SimpleFactory idea, and what you found was that the franchises were using your factory to create pizzas, but starting to employ their own home grown procedures for the rest of the process: they’d bake things a little differently, they’d forget to cut the pizza and they’d use third-party boxes.

Rethinking the problem a bit, you see that what you’d really like to do is create a framework that ties the store and the pizza creation together, yet still allows things to remain flexible.

In our early code, before the SimplePizzaFactory, we had the pizza-making code tied to the PizzaStore, but it wasn’t flexible. So, how can we have our pizza and eat it too?

image with no caption

A framework for the pizza store

There is a way to localize all the pizza making activities to the PizzaStore class, and yet give the franchises freedom to have their own regional style.

What we’re going to do is put the createPizza() method back into PizzaStore, but this time as an abstract method, and then create a PizzaStore subclass for each regional style.

First, let’s look at the changes to the PizzaStore:

image with no caption

Now we’ve got a store waiting for subclasses; we’re going to have a subclass for each regional type (NYPizzaStore, ChicagoPizzaStore, CaliforniaPizzaStore) and each subclass is going to make the decision about what makes up a pizza. Let’s take a look at how this is going to work.

Allowing the subclasses to decide

Remember, the PizzaStore already has a well-honed order system in the orderPizza() method and you want to ensure that it’s consistent across all franchises.

What varies among the regional PizzaStores is the style of pizzas they make – New York Pizza has thin crust, Chicago Pizza has thick, and so on – and we are going to push all these variations into the createPizza() method and make it responsible for creating the right kind of pizza. The way we do this is by letting each subclass of PizzaStore define what the createPizza() method looks like. So, we will have a number of concrete subclasses of PizzaStore, each with its own pizza variations, all fitting within the PizzaStore framework and still making use of the well-tuned orderPizza() method.

image with no caption
image with no caption

Well, think about it from the point of view of the PizzaStore’s orderPizza() method: it is defined in the abstract PizzaStore, but concrete types are only created in the subclasses.

image with no caption

Now, to take this a little further, the orderPizza() method does a lot of things with a Pizza object (like prepare, bake, cut, box), but because Pizza is abstract, orderPizza() has no idea what real concrete classes are involved. In other words, it’s decoupled!

image with no caption

When orderPizza() calls createPizza(), one of your subclasses will be called into action to create a pizza. Which kind of pizza will be made? Well, that’s decided by the choice of pizza store you order from, NYStylePizzaStore or ChicagoStylePizzaStore.

image with no caption

So, is there a real-time decision that subclasses make? No, but from the perspective of orderPizza(), if you chose a NYStylePizzaStore, that subclass gets to determine which pizza is made. So the subclasses aren’t really “deciding” – it was you who decided by choosing which store you wanted – but they do determine which kind of pizza gets made.

Let’s make a PizzaStore

Being a franchise has its benefits. You get all the PizzaStore functionality for free. All the regional stores need to do is subclass PizzaStore and supply a createPizza() method that implements their style of Pizza. We’ll take care of the big three pizza styles for the franchisees.

Here’s the New York regional style:

image with no caption


* Note that the orderPizza() method in the superclass has no clue which Pizza we are creating; it just knows it can prepare, bake, cut, and box it!

Once we’ve got our PizzaStore subclasses built, it will be time to see about ordering up a pizza or two. But before we do that, why don’t you take a crack at building the Chicago Style and California Style pizza stores on the next page.

Declaring a factory method

With just a couple of transformations to the PizzaStore we’ve gone from having an object handle the instantiation of our concrete classes to a set of subclasses that are now taking on that responsibility. Let’s take a closer look:

image with no caption

Let’s see how it works: ordering pizzas with the pizza factory method

image with no caption

So how do they order?

  1. First, Joel and Ethan need an instance of a PizzaStore. Joel needs to instantiate a ChicagoPizzaStore and Ethan needs a NYPizzaStore.

  2. With a PizzaStore in hand, both Ethan and Joel call the orderPizza() method and pass in the type of pizza they want (cheese, veggie, and so on).

  3. To create the pizzas, the createPizza() method is called, which is defined in the two subclasses NYPizzaStore and ChicagoPizzaStore. As we defined them, the NYPizzaStore instantiates a NY style pizza, and the ChicagoPizzaStore instantiates Chicago style pizza. In either case, the Pizza is returned to the orderPizza() method.

  4. The orderPizza() method has no idea what kind of pizza was created, but it knows it is a pizza and it prepares, bakes, cuts, and boxes it for Ethan and Joel.

Let’s check out how these pizzas are really made to order...

image with no caption

Behind the Scenes

image with no caption

We’re just missing one thing: PIZZA!

image with no caption

Our PizzaStore isn’t going to be very popular without some pizzas, so let’s implement them

image with no caption


REMEMBER: we don’t provide import and package statements in the code listings. Get the complete source code from the wickedlysmart web site. You’ll find the URL on Read Me in the Intro.

Now we just need some concrete subclasses... how about defining New York and Chicago style cheese pizzas?

image with no caption

You’ve waited long enough, time for some pizzas!

image with no caption
image with no caption

It’s finally time to meet the Factory Method Pattern

All factory patterns encapsulate object creation. The Factory Method Pattern encapsulates object creation by letting subclasses decide what objects to create. Let’s check out these class diagrams to see who the players are in this pattern:

The Creator classes

image with no caption

The Product classes

image with no caption

Another perspective: parallel class hierarchies

We’ve seen that the factory method provides a framework by supplying an orderPizza() method that is combined with a factory method. Another way to look at this pattern as a framework is in the way it encapsulates product knowledge into each creator.

Let’s look at the two parallel class hierarchies and see how they relate:

image with no caption

Factory Method Pattern defined

It’s time to roll out the official definition of the Factory Method Pattern:


The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

As with every factory, the Factory Method Pattern gives us a way to encapsulate the instantiations of concrete types. Looking at the class diagram below, you can see that the abstract Creator gives you an interface with a method for creating objects, also known as the “factory method.” Any other methods implemented in the abstract Creator are written to operate on products produced by the factory method. Only subclasses actually implement the factory method and create products.

As in the official definition, you’ll often hear developers say that the Factory Method lets subclasses decide which class to instantiate. They say “decide” not because the pattern allows subclasses themselves to decide at runtime, but because the creator class is written without knowledge of the actual products that will be created, which is decided purely by the choice of the subclass that is used.


You could ask them what “decides” means, but we bet you now understand this better than they do!

image with no caption

A very dependent PizzaStore

Looking at object dependencies

When you directly instantiate an object, you are depending on its concrete class. Take a look at our very dependent PizzaStore one page back. It creates all the pizza objects right in the PizzaStore class instead of delegating to a factory.

If we draw a diagram representing that version of the PizzaStore and all the objects it depends on, here’s what it looks like:

image with no caption

The Dependency Inversion Principle

It should be pretty clear that reducing dependencies to concrete classes in our code is a “good thing.” In fact, we’ve got an OO design principle that formalizes this notion; it even has a big, formal name: Dependency Inversion Principle.


Yet another phrase you can use to impress the execs in the room! Your raise will more than offset the cost of this book, and you’ll gain the admiration of your fellow developers.

Here’s the general principle:


Design Principle

Depend upon abstractions. Do not depend upon concrete classes.

At first, this principle sounds a lot like “Program to an interface, not an implementation,” right? It is similar; however, the Dependency Inversion Principle makes an even stronger statement about abstraction. It suggests that our high-level components should not depend on our low-level components; rather, they should both depend on abstractions.


A “high-level” component is a class with behavior defined in terms of other, “low level” components. For example, PizzaStore is a high-level component because its behavior is defined in terms of pizzas - it creates all the different pizza objects, prepares, bakes, cuts, and boxes them, while the pizzas it uses are low-level components.

But what the heck does that mean?

Well, let’s start by looking again at the pizza store diagram on the previous page. PizzaStore is our “high-level component” and the pizza implementations are our “low-level components,” and clearly the PizzaStore is dependent on the concrete pizza classes.

Now, this principle tells us we should instead write our code so that we are depending on abstractions, not concrete classes. That goes for both our high level modules and our low-level modules.

But how do we do this? Let’s think about how we’d apply this principle to our Very Dependent PizzaStore implementation...

Applying the Principle

Now, the main problem with the Very Dependent PizzaStore is that it depends on every type of pizza because it actually instantiates concrete types in its orderPizza() method.

While we’ve created an abstraction, Pizza, we’re nevertheless creating concrete Pizzas in this code, so we don’t get a lot of leverage out of this abstraction.

How can we get those instantiations out of the orderPizza() method? Well, as we know, the Factory Method allows us to do just that.

So, after we’ve applied the Factory Method, our diagram looks like this:

image with no caption

After applying the Factory Method, you’ll notice that our high-level component, the PizzaStore, and our low-level components, the pizzas, both depend on Pizza, the abstraction. Factory Method is not the only technique for adhering to the Dependency Inversion Principle, but it is one of the more powerful ones.

image with no caption

Where’s the “inversion” in Dependency Inversion Principle?

The “inversion” in the name Dependency Inversion Principle is there because it inverts the way you typically might think about your OO design. Look at the diagram on the previous page, notice that the low-level components now depend on a higher level abstraction. Likewise, the high-level component is also tied to the same abstraction. So, the top-to-bottom dependency chart we drew a couple of pages back has inverted itself, with both high-level and low-level modules now depending on the abstraction.

Let’s also walk through the thinking behind the typical design process and see how introducing the principle can invert the way we think about the design...

Inverting your thinking...

Okay, so you need to implement a PizzaStore. What’s the first thought that pops into your head?

Right, you start at top and follow things down to the concrete classes. But, as you’ve seen, you don’t want your store to know about the concrete pizza types, because then it’ll be dependent on all those concrete classes!

Now, let’s “invert” your thinking... instead of starting at the top, start at the Pizzas and think about what you can abstract.

Right! You are thinking about the abstraction Pizza. So now, go back and think about the design of the Pizza Store again.

Close. But to do that you’ll have to rely on a factory to get those concrete classes out of your Pizza Store. Once you’ve done that, your different concrete pizza types depend only on an abstraction and so does your store. We’ve taken a design where the store depended on concrete classes and inverted those dependencies (along with your thinking).

A few guidelines to help you follow the Principle...

The following guidelines can help you avoid OO designs that violate the Dependency Inversion Principle:

  • No variable should hold a reference to a concrete class.


    If you use new, you’ll be holding a reference to a concrete class. Use a factory to get around that!

  • No class should derive from a concrete class.


    If you derive from a concrete class, you’re depending on a concrete class. Derive from an abstraction, like an interface or an abstract class.

  • No method should override an implemented method of any of its base classes.


    If you override an implemented method, then your base class wasn’t really an abstraction to start with. Those methods implemented in the base class are meant to be shared by all your subclasses.

image with no caption

You’re exactly right! Like many of our principles, this is a guideline you should strive for, rather than a rule you should follow all the time. Clearly, every single Java program ever written violates these guidelines!

But, if you internalize these guidelines and have them in the back of your mind when you design, you’ll know when you are violating the principle and you’ll have a good reason for doing so. For instance, if you have a class that isn’t likely to change, and you know it, then it’s not the end of the world if you instantiate a concrete class in your code. Think about it; we instantiate String objects all the time without thinking twice. Does that violate the principle? Yes. Is that okay? Yes. Why? Because String is very unlikely to change.

If, on the other hand, a class you write is likely to change, you have some good techniques like Factory Method to encapsulate that change.

Meanwhile, back at the PizzaStore...

The design for the PizzaStore is really shaping up: it’s got a flexible framework and it does a good job of adhering to design principles.

Now, the key to Objectville Pizza’s success has always been fresh, quality ingredients, and what you’ve discovered is that with the new framework your franchises have been following your procedures, but a few franchises have been substituting inferior ingredients in their pies to lower costs and increase their margins. You know you’ve got to do something, because in the long term this is going to hurt the Objectville brand!

image with no caption

Ensuring consistency in your ingredients

So how are you going to ensure each franchise is using quality ingredients? You’re going to build a factory that produces them and ships them to your franchises!

Now there is only one problem with this plan: the franchises are located in different regions and what is red sauce in New York is not red sauce in Chicago. So, you have one set of ingredients that needs to be shipped to New York and a different set that needs to be shipped to Chicago. Let’s take a closer look:

image with no caption

Families of ingredients...

New York uses one set of ingredients and Chicago another. Given the popularity of Objectville Pizza it won’t be long before you also need to ship another set of regional ingredients to California, and what’s next? Seattle?

For this to work, you are going to have to figure out how to handle families of ingredients.

image with no caption

Building the ingredient factories

Now we’re going to build a factory to create our ingredients; the factory will be responsible for creating each ingredient in the ingredient family. In other words, the factory will need to create dough, sauce, cheese, and so on... You’ll see how we are going to handle the regional differences shortly.

Let’s start by defining an interface for the factory that is going to create all our ingredients:

image with no caption


If we’d had some common “machinery” to implement in each instance of factory, we could have made this an abstract class instead...

Here’s what we’re going to do:

  1. Build a factory for each region. To do this, you’ll create a subclass of PizzaIngredientFactory that implements each create method

  2. Implement a set of ingredient classes to be used with the factory, like ReggianoCheese, RedPeppers, and ThickCrustDough. These classes can be shared among regions where appropriate.

  3. Then we still need to hook all this up by working our new ingredient factories into our old PizzaStore code.

Building the New York ingredient factory

Okay, here’s the implementation for the New York ingredient factory. This factory specializes in Marinara sauce, Reggiano Cheese, Fresh Clams...

image with no caption

Reworking the pizzas...

We’ve got our factories all fired up and ready to produce quality ingredients; now we just need to rework our Pizzas so they only use factory-produced ingredients. We’ll start with our abstract Pizza class:

image with no caption

Now that you’ve got an abstract Pizza to work from, it’s time to create the New York and Chicago style Pizzas – only this time around they will get their ingredients straight from the factory. The franchisees’ days of skimping on ingredients are over!

When we wrote the Factory Method code, we had a NYCheesePizza and a ChicagoCheesePizza class. If you look at the two classes, the only thing that differs is the use of regional ingredients. The pizzas are made just the same (dough + sauce + cheese). The same goes for the other pizzas: Veggie, Clam, and so on. They all follow the same preparation steps; they just have different ingredients.

So, what you’ll see is that we really don’t need two classes for each pizza; the ingredient factory is going to handle the regional differences for us. Here’s the Cheese Pizza:

image with no caption

Let’s check out the ClamPizza as well:

image with no caption

Revisiting our pizza stores

We’re almost there; we just need to make a quick trip to our franchise stores to make sure they are using the correct Pizzas. We also need to give them a reference to their local ingredient factories:

image with no caption

Brain Power

Compare this version of the createPizza() method to the one in the Factory Method implementation earlier in the chapter.

What have we done?

That was quite a series of code changes; what exactly did we do?

We provided a means of creating a family of ingredients for pizzas by introducing a new type of factory called an Abstract Factory.

An Abstract Factory gives us an interface for creating a family of products. By writing code that uses this interface, we decouple our code from the actual factory that creates the products. That allows us to implement a variety of factories that produce products meant for different contexts – such as different regions, different operating systems, or different look and feels.

Because our code is decoupled from the actual products, we can substitute different factories to get different behaviors (like getting marinara instead of plum tomatoes).

An Abstract Factory provides an interface for a family of products. What’s a family? In our case it’s all the things we need to make a pizza: dough, sauce, cheese, meats and veggies.

image with no caption

We then write our code so that it uses the factory to create products. By passing in a variety of factories, we get a variety of implementations of those products. But our client code stays the same.

More pizza for Ethan and Joel...

image with no caption

Behind the Scenes

Ethan and Joel can’t get enough Objectville Pizza! What they don’t know is that now their orders are making use of the new ingredient factories. So now when they order...

image with no caption

The first part of the order process hasn’t changed at all. Let’s follow Ethan’s order again:

image with no caption

From here things change, because we are using an ingredient factory

image with no caption

Behind the Scenes

image with no caption

Abstract Factory Pattern defined

We’re adding yet another factory pattern to our pattern family, one that lets us create families of products. Let’s check out the official definition for this pattern:


The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.

We’ve certainly seen that Abstract Factory allows a client to use an abstract interface to create a set of related products without knowing (or caring) about the concrete products that are actually produced. In this way, the client is decoupled from any of the specifics of the concrete products. Let’s look at the class diagram to see how this all holds together:

image with no caption

That’s a fairly complicated class diagram; let’s look at it all in terms of our PizzaStore:

image with no caption
image with no caption

Is that a Factory Method lurking inside the Abstract Factory?

Good catch! Yes, often the methods of an Abstract Factory are implemented as factory methods. It makes sense, right? The job of an Abstract Factory is to define an interface for creating a set of products. Each method in that interface is responsible for creating a concrete product, and we implement a subclass of the Abstract Factory to supply those implementations. So, factory methods are a natural way to implement your product methods in your abstract factories.

Factory Method and Abstract Factory compared

image with no caption
image with no caption

Tools for your Design Toolbox

In this chapter, we added two more tools to your toolbox: Factory Method and Abstract Factory. Both patterns encapsulate object creation and allow you to decouple your code from concrete types.

image with no caption
image with no caption

Exercise Solutions

A very dependent PizzaStore

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