Design_Patterns_For_Dummies
There are plenty of design patterns floating around the programming world,
and in time, a particular set of 23 of them has become accepted as the stan-
dard set. These patterns were first corralled in a book named Design Patterns:
Elements of Reusable Object-Oriented Software (1995, Pearson Education, Inc.
Publishing as Pearson Addison Wesley) by Erich Gamma, Richard Helm,
Ralph Johnson, and John Vlissides — who have since been called the Gang of
Four, or GoF, for short. And those 23 design patterns became known as the
GoF design patterns....
Design Patterns
FOR
DUMmIES
‰
by Steve Holzner, PhD
Design Patterns
FOR
DUMmIES
‰
Design Patterns
FOR
DUMmIES
‰
by Steve Holzner, PhD
Design Patterns For Dummies®
Published by
Wiley Publishing, Inc.
111 River Street
Hoboken, NJ 07030-5774
www.wiley.com
Copyright © 2006 by Wiley Publishing, Inc., Indianapolis, Indiana
Gamma/Helm/Johnson/Vlissides, DESIGN PATTERNS: ELEMENTS OF REUSABLE OBJECT-ORIENTED
SOFTWARE, © 1995 Pearson Education, Inc. Reprinted by permission of Pearson Education, Inc. Publishing
as Pearson Addison Wesley.
Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or
by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permit-
ted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written
permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the
Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600.
Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing,
Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at
http://www.wiley.com/go/permissions.
Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the
Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, and related trade
dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United
States and other countries, and may not be used without written permission. All other trademarks are the
property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor
mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REP-
RESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CON-
TENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT
LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CRE-
ATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CON-
TAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE
UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR
OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A
COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE
AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION
OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FUR-
THER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFOR-
MATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE.
FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE
CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services, please contact our Customer Care
Department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.
For technical support, please visit www.wiley.com/techsupport.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may
not be available in electronic books.
Library of Congress Control Number: 2006920631
ISBN-13: 978-0-471-79854-5
ISBN-10: 0-471-79854-1
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
1B/RX/QU/QW/IN
About the Author
Steve Holzner is the award-winning author of 100 books on computing.
He’s a former contributing editor for PC Magazine, and has been on the
faculty of Cornell University and MIT. In addition to his busy writing sched-
ule, he gives programming classes to corporate programmers around
the country and runs his own training company, which you can find at
http://www.onsiteglobal.com/.
Dedication
To Nancy, as always and forever.
Author’s Acknowledgments
The book you hold in your hands is the result of many peoples’ work. I would
particularly like to thank Mark Enochs, editor extraordinaire, and Katie
Feltman, my acquisitions editor, who helped get this book off the ground and
keep it in flight the rest of the way. Thanks also to my copy editor, Heidi
Unger, for dotting the I’s and crossing the T’s.
Publisher’s Acknowledgments
We’re proud of this book; please send us your comments through our online registration form
located at www.dummies.com/register/.
Some of the people who helped bring this book to market include the following:
Acquisitions, Editorial, and Composition
Media Development Project Coordinator: Tera Knapp
Project Editor: Mark Enochs Layout and Graphics: Carl Byers, Andrea Dahl,
Acquisitions Editor: Katie Feltman Lauren Goddard, Heather Ryan
Copy Editor: Heidi Unger Proofreaders: Debbye Butler,
Technical Editor: John Purdum Christine Pingleton
Editorial Manager: Leah Cameron Indexer: Techbooks
Media Development Coordinator:
Laura Atkinson
Media Project Supervisor: Laura Moss
Media Development Manager: Laura VanWinkle
Editorial Assistant: Amanda Foxworth
Cartoons: Rich Tennant
(www.the5thwave.com)
Publishing and Editorial for Technology Dummies
Richard Swadley, Vice President and Executive Group Publisher
Andy Cummings, Vice President and Publisher
Mary Bednarek, Executive Acquisitions Director
Mary C. Corder, Editorial Director
Publishing for Consumer Dummies
Diane Graves Steele, Vice President and Publisher
Joyce Pepple, Acquisitions Director
Composition Services
Gerry Fahey, Vice President of Production Services
Debbie Stailey, Director of Composition Services
Contents at a Glance
Introduction .................................................................1
Part I: Getting to Know Patterns....................................5
Chapter 1: Congratulations, Your Problem Has Already Been Solved.........................7
Chapter 2: Putting Plans into Action with the Strategy Pattern.................................17
Chapter 3: Creating and Extending Objects with the Decorator and
Factory Patterns.............................................................................................................39
Chapter 4: Watch What’s Going On with the Observer and
Chain of Responsibility Patterns .................................................................................65
Chapter 5: From One to Many: The Singleton and Flyweight Patterns......................91
Part II: Becoming an OOP Master ..............................117
Chapter 6: Fitting Round Pegs into Square Holes with the Adapter and
Facade Patterns............................................................................................................119
Chapter 7: Mass Producing Objects with the Template Method and
Builder Patterns ..........................................................................................................145
Chapter 8: Handling Collections with the Iterator and Composite Patterns .........177
Chapter 9: Getting Control of Your Objects with the State and Proxy Patterns ...207
Chapter 10: Coordinating Your Objects with the Command and Mediator
Patterns .........................................................................................................................233
Part III: The Part of Tens...........................................257
Chapter 11: Ten More Design Patterns .......................................................................259
Chapter 12: Ten Easy Steps to Create Your Own Patterns ........................................281
Index .......................................................................295
Table of Contents
Introduction..................................................................1
About This Book...............................................................................................1
Foolish Assumptions .......................................................................................2
Conventions Used in This Book .....................................................................2
How This Book Is Organized...........................................................................3
Part I: Getting to Know Patterns...........................................................3
Part II: Becoming an OOP Master .........................................................3
Part III: The Part of Tens........................................................................4
Icons Used in This Book..................................................................................4
Where to Go from Here....................................................................................4
Part I: Getting to Know Patterns ....................................5
Chapter 1: Congratulations, Your Problem
Has Already Been Solved . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7
Just Find the Pattern that Fits ........................................................................8
Enter the Gang of Four Book...........................................................................9
Getting Started: The Mediator Pattern........................................................10
Adapting to the Adapter Pattern..................................................................11
Standing In for Other Objects with the Proxy Pattern ..............................12
Taking a Look at the Observer Pattern .......................................................13
Chapter 2: Putting Plans into Action with the Strategy Pattern . . . . .17
Extending Object-Oriented Programming...................................................18
The big four OOP building blocks ......................................................19
Abstraction is the good kind of breakdown ............................19
Encapsulating all that junk ........................................................20
Mighty polymorphism rangers .................................................20
Inheritance without the pesky taxes........................................22
Composition versus inheritance: A first attempt
at designing the new cars ................................................................23
Handling Change with “has-a” Instead of “is-a”..........................................27
Drawing Up Your Plans..................................................................................29
Creating your algorithms.....................................................................29
Using your algorithms .........................................................................30
Selecting algorithms at runtime .........................................................33
Making Your Move with the Strategy Pattern.............................................35
xiv Design Patterns For Dummies
Chapter 3: Creating and Extending Objects
with the Decorator and Factory Patterns . . . . . . . . . . . . . . . . . . . . . . . .39
Closed for Modification, Open for Extension .............................................41
Enter the Decorator Pattern .........................................................................42
Putting the Decorator Pattern to Work .......................................................45
Creating a decorator ............................................................................45
Adding a disk ........................................................................................46
Adding a CD...........................................................................................47
Adding a monitor..................................................................................47
Testing it out .........................................................................................48
Improving the New Operator with the Factory Pattern ............................50
Building Your First Factory...........................................................................52
Creating the factory .............................................................................53
Creating the abstract Connection class ............................................54
Creating the concrete connection classes ........................................55
Testing it out .........................................................................................56
Creating a Factory the GoF Way ...................................................................59
Creating an abstract factory ...............................................................59
Creating a concrete factory.................................................................60
Creating the secure connection classes ............................................61
Testing it out .........................................................................................62
Chapter 4: Watch What’s Going On with the Observer
and Chain of Responsibility Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . .65
Notifying Observers with the Observer Pattern ........................................66
Creating a subject interface ................................................................69
Creating an observer interface ...........................................................70
Creating a subject.................................................................................70
Creating observers...............................................................................73
Testing the Database observers .........................................................75
Using Java’s Observer Interface and Observable Class............................78
Watching with the Observer interface...............................................78
Notifying with the Observable class..................................................79
Creating the Observable object..........................................................80
Creating the Observer objects............................................................82
Testing the Observable code ..............................................................84
Using the Chain of Responsibility Pattern ..................................................86
Creating a help interface .....................................................................87
Creating chainable objects..................................................................87
Testing the Help system ......................................................................89
Table of Contents xv
Chapter 5: From One to Many: The Singleton
and Flyweight Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91
Instantiating Just One Object with the Singleton Pattern.........................92
Creating a Singleton-based database .................................................94
Testing the Singleton pattern..............................................................98
Uh oh, don’t forget about multithreading .........................................99
Putting the synchronized solution to work ....................................100
Handling threading better .................................................................103
Putting the pre-thread solution to work..........................................104
The Flyweight Pattern Makes One Look like Many..................................106
Creating a student ..............................................................................109
Testing the Flyweight pattern ...........................................................110
Handling threading better .................................................................112
Part II: Becoming an OOP Master ...............................117
Chapter 6: Fitting Round Pegs into Square Holes
with the Adapter and Facade Patterns . . . . . . . . . . . . . . . . . . . . . . . . .119
The Adapter Scenario..................................................................................119
Fixing Connection Problems with Adapters .............................................121
Creating Ace objects ..........................................................................123
Creating Acme objects.......................................................................124
Creating an Ace-to-Acme object adapter.........................................125
Testing the adapter ............................................................................127
Inheriting class adapters ...................................................................128
Simplifying Life with Facades .....................................................................134
Dealing with a difficult object ...........................................................137
Creating a simplifying facade ...........................................................140
Testing the facade ..............................................................................143
Chapter 7: Mass Producing Objects with the
Template Method and Builder Patterns . . . . . . . . . . . . . . . . . . . . . . . .145
Creating the First Robot ..............................................................................146
Creating Robots with the Template Method Pattern...............................149
Creating robots by template .............................................................150
Testing the creation of robots ..........................................................155
Built-in Template Methods in Java ...................................................156
xvi Design Patterns For Dummies
Adding a hook .....................................................................................158
Testing the hook method ..................................................................160
Building Robots with the Builder Pattern .................................................161
The client rules...................................................................................161
Letting clients build robots...............................................................165
Creating some buildable robots .......................................................168
Testing the robot builder ..................................................................172
Chapter 8: Handling Collections with the
Iterator and Composite Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .177
Accessing Objects with the Iterator Pattern ............................................178
Accessing your objects with an iterator .........................................179
Gathering the vice presidents into a collection .............................181
Creating the iterator...........................................................................183
Iterating over vice presidents...........................................................186
More fun with for/in ...........................................................................190
Putting Together Composites.....................................................................191
It all starts with an abstract class ....................................................193
Creating the vice president leaves ...................................................194
Creating the division branches.........................................................196
Building your corporation.................................................................198
Tracking the Composite Pattern in the Wild ............................................203
Chapter 9: Getting Control of Your Objects
with the State and Proxy Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . .207
Getting the State of Your Union with the State Pattern...........................208
Using methods to hold state.............................................................209
Using objects to encapsulate state ..................................................213
Creating the state objects .................................................................218
Putting the rental automat to the test .............................................223
Standing In for Other Objects with Proxies ..............................................224
Can you hear me now? Creating the automat server ....................225
Anyone there? Creating the automat proxy ....................................228
Using the proxy to connect around the world................................230
Chapter 10: Coordinating Your Objects with the
Command and Mediator Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .233
Taking Command with the Command Pattern .........................................234
Aiming at the target: Creating your receiver objects.....................236
Be the boss: Creating your commands............................................239
Getting your commands to actually do something:
Creating the invoker .......................................................................241
Table of Contents xvii
Putting commands to the test ..........................................................242
Supporting undo.................................................................................244
Testing the undo.................................................................................247
Coordinating with the Mediator Pattern ...................................................249
Designing the Rutabagas-R-Us site ...................................................251
Connecting it all up with the mediator............................................254
Testing the Rutabagas-R-Us site .......................................................255
Part III: The Part of Tens ...........................................257
Chapter 11: Ten More Design Patterns . . . . . . . . . . . . . . . . . . . . . . . . .259
Creating a Factory Factory: The Abstract Factory Pattern ....................260
Cloning when You Need It: The Prototype Pattern ..................................261
Decoupling Abstractions from Implementations
with the Bridge Pattern ...........................................................................262
Creating Your Own Language: The Interpreter Pattern...........................264
Forget Me Not: The Memento Pattern .......................................................264
The Visitor Stops In for a Moment .............................................................266
Going in Circles with Circular Buffers .......................................................268
Doing Your Magic Off-Screen with the Double Buffer Pattern................274
Getting Multiple-Use Objects Out of the
Recycle Bin Design Pattern .....................................................................277
Entering the Big Time with the Model/View/Controller Pattern............278
Chapter 12: Ten Easy Steps to Create Your Own Patterns . . . . . . . . .281
Following the Pattern Catalog Style...........................................................283
Introducing the Veto Pattern ......................................................................283
1. Intent ................................................................................................284
2. Motivation .......................................................................................285
3. Applicability....................................................................................285
4. Structure..........................................................................................285
5. Participants .....................................................................................286
6. Collaborations ................................................................................287
7. Consequences.................................................................................287
8. Implementation/Sample Code ......................................................288
9. Known Uses.....................................................................................292
10. Related Patterns ...........................................................................293
Getting Your Pattern into a Pattern Catalog .............................................293
Index........................................................................295