(Head First Series) Eric Freeman - Elisabeth Robson - Head First Design Patterns - Building Extensible and Maintainable Object-Oriented Software (2021, O'Reilly Media) - Libgen - Li
(Head First Series) Eric Freeman - Elisabeth Robson - Head First Design Patterns - Building Extensible and Maintainable Object-Oriented Software (2021, O'Reilly Media) - Libgen - Li
a. W ho i s t hi s b ook f or ?
i . W ho shoul d pr ob ab l y b ac k aw ay f r om
t hi s b ook ?
h. Tec h Rev i ew er s
i . Tec h Rev i ew er s, 2nd Edi t i on
j. A c k now l edgment s
i . Fr om t he f i r st edi t i on
k . A c k now l edgment s
i . The Sw i ng l i b r ar y
i i . A l i t t l e l i f e-c hangi ng appl i c at i on
i . A f r amew or k f or t he pi zza st or e
j. A l l ow i ng t he sub c l asses t o dec i de
k . Let ’s mak e a Pi zza St or e
l . Dec l ar i ng a f ac t or y met hod
a. The Li t t l e Si ngl et on
i . A smal l Soc r at i c ex er c i se i n t he st y l e
of The Li t t l e Li sper
i . N ow , l et ’s c hec k out t he ex ec ut i on of
our r emot e c ont r ol t est ...
a. A dapt er s al l ar ound us
b . Ob jec t -or i ent ed adapt er s
c . If i t w al k s l i k e a duc k and quac k s l i k e a duc k ,
t hen i t must mi ght b e a duc k t ur k ey w r apped
w i t h a duc k adapt er ...
d. Test dr i v e t he adapt er
e. The A dapt er Pat t er n ex pl ai ned
i . Enumer at or s
i i . It er at or s
i i i . U si ng Enumer at or s w i t h c ode t hat
ex pec t s It er at or s
l . A dapt i ng an Enumer at i on t o an It er at or
i . A nd l et ’s gi v e i t a r un...
i . Fi x i ng t he pr i nt () met hod
a. Jav a Br eak er s
b . Cub i c l e Conv er sat i on
c . St at e mac hi nes 1 01
d. W r i t i ng t he c ode
e. In-house t est i ng
f . You k new i t w as c omi ng...a c hange r equest !
g. Desi gn Puzzl e
h. The messy STA TE of t hi ngs...
i . The new desi gn
j. Def i ni ng t he St at e i nt er f ac es and c l asses
k . Impl ement i ng our St at e c l asses
l . Rew or k i ng t he Gumb al l Mac hi ne
m. N ow , l et ’s l ook at t he c ompl et e
Gumb al l Mac hi ne c l ass...
n. Impl ement i ng mor e st at es
o. Let ’s t ak e a l ook at w hat w e’v e done so f ar ...
p. The St at e Pat t er n def i ned
q. t her e ar e no Dumb Quest i ons
r . W e st i l l need t o f i ni sh t he Gumb al l 1 i n 1 0 game
s. Fi ni shi ng t he game
a. Codi ng t he Moni t or
b . Test i ng t he Moni t or
i . The r ol e of t he ‘r emot e pr ox y ’
i . W al k i ng t hr ough t he desi gn
w . Di spl ay i ng A l b um c ov er s
x . Desi gni ng t he A l b um Cov er V i r t ual Pr ox y
y . W r i t i ng t he Image Pr ox y
z. Test i ng t he A l b um Cov er V i ew er
a. W or k i ng t oget her
b . Duc k r euni on
c . t her e ar e no Dumb Quest i ons
d. W hat di d w e do?
e. A duc k ’s-ey e v i ew : t he c l ass di agr am
f . The Ki ng of Compound Pat t er ns
i . If El v i s w er e a c ompound pat t er n, hi s
name w oul d b e Model -V i ew -
Cont r ol l er , and he’d b e si ngi ng a l i t t l e
song l i k e t hi s...
i . Meet t he Jav a DJ V i ew
i i . The c ont r ol l er i s i n t he mi ddl e...
i i i . Let ’s not f or get ab out t he model
under neat h i t al l ...
v . Ex pl or i ng St r at egy
w . A dapt i ng t he Model
x . N ow w e’r e r eady f or a Hear t Cont r ol l er
i . A nd t hat ’s i t ! N ow i t ’s t i me f or some
t est c ode...
i . Thi ngs t o t r y
z. t her e ar e no Dumb Quest i ons
aa. Tool s f or y our Desi gn Tool b ox
ab . Ex er c i se Sol ut i ons
h. Your Mi nd on Pat t er ns
i . Don’t f or get t he pow er of t he shar ed v oc ab ul ar y
j. Cr ui si n’ Ob jec t v i l l e w i t h t he Gang of Four
k . Your jour ney has just b egun...
1 7 . A . Lef t ov er Pat t er ns
a. Br i dge
i . Your di l emma
i . A sc enar i o
i i . Your t ask
i . A sc enar i o
i i . Your b i g c l i ent ’s di l emma
i . A sc enar i o
i i . N ow w hat ?
i . A sc enar i o
i i . HouseOf TheFut ur e’s di l emma
l . Medi at or i n ac t i on...
m. Mement o
i . A sc enar i o
n. The Mement o at w or k
o. Pr ot ot y pe
i . A sc enar i o
p. Pr ot ot y pe t o t he r esc ue
q. V i si t or
i . A sc enar i o
r . The V i si t or dr ops b y
1 8. Index
Head First Design Patterns
Eric Freeman
Elisabeth Robson
Head F irst Design Patterns, 2nd Edition
Pr i nt ed i n Canada.
O’Rei l l y Medi a b ook s may b e pur c hased f or educ at i onal , b usi ness,
or sal es pr omot i onal use. Onl i ne edi t i ons ar e al so av ai l ab l e f or
most t i t l es (oreilly .c om (http://oreilly.com) ). For mor e i nf or mat i on,
c ont ac t our c or por at e/i nst i t ut i onal sal es depar t ment : (800) 998-
9938 or c orporate@oreilly .c om .
Printing History :
Oc t ob er 2004: Fi r st edi t i on
Release History :
2020-1 1 -1 0 Fi r st r el ease
W her e t hose desi gnat i ons appear i n t hi s b ook , and O’Rei l l y Medi a,
Inc . w as aw ar e of a t r ademar k c l ai m, t he desi gnat i ons hav e b een
pr i nt ed i n c aps or i ni t i al c aps.
The or i gi nal GoF agr eed t o hav e t hei r phot os i n t hi s b ook . Yes, t hey
r eal l y ar e t hat good-l ook i ng.
In 2003, Ber t and Kat hy w r ot e Head Firs t Jav a and l aunc hed t he
Head Fi r st ser i es. Si nc e t hen, he’s w r i t t en mor e Jav a b ook s, and
c onsul t ed w i t h Sun Mi c r osy st ems and Or ac l e on many of t hei r Jav a
c er t i f i c at i ons. He’s al so t r ai ned hundr eds of aut hor s and edi t or s t o
c r eat e b ook s t hat t eac h w el l .
W ho i s t hi s b ook f or ?
Read Me
Tec h Rev i ew er s
A c k now l edgment s
How ab out an i nt er f ac e?
Zer oi ng i n on t he pr ob l em…
Ov er hear d at t he l oc al di ner …
Ov er hear d i n t he nex t c ub i c l e…
W r i t i ng t he St ar b uzz c ode
Codi ng b ev er ages
A f r amew or k f or t he pi zza st or e
A ppl y i ng t he Pr i nc i pl e
Rew or k i ng t he pi zzas…
U si ng t he c ommand ob jec t
U si ng a mac r o c ommand
A dapt er s al l ar ound us
Test dr i v e t he adapt er
Real -w or l d adapt er s
A dapt i ng an Enumer at i on t o an It er at or
W at c hi ng a mov i e (t he har d w ay )
Ti me t o w at c h a mov i e (t he easy w ay )
It ’s t i me f or some mor e c af f ei ne
U si ng t he hook
Sw i ngi n’ w i t h Fr ames
Cust om Li st s w i t h A b st r ac t Li st
Meet t he It er at or Pat t er n
Fi x i ng up t he W ai t r ess c ode
The It er at or Pat t er n St r uc t ur e
N ow f or t he t est dr i v e…
Jav a Br eak er s
St at e mac hi nes 1 01
W r i t i ng t he c ode
In-house t est i ng
N ow , l et ’s l ook at t he c ompl et e
Gumb al l Mac hi ne c l ass…
Fi ni shi ng t he game
Sani t y c hec k …
W e al most f or got !
Codi ng t he Moni t or
Test i ng t he Moni t or
W r i t i ng t he Image Pr ox y
Bi g Pi c t ur e: c r eat i ng a Dy nami c Pr ox y f or t he
Per son
The Pr ox y Zoo
W or k i ng t oget her
Duc k r euni on
W hat di d w e do?
A c l oser l ook …
U si ng MV C t o c ont r ol t he b eat …
Bui l di ng t he pi ec es
The V i ew
Impl ement i ng t he V i ew
N ow f or t he Cont r ol l er
Ex pl or i ng St r at egy
A dapt i ng t he Model
May t he f or c e b e w i t h y ou
Thi nk i ng i n Pat t er ns
Your Mi nd on Pat t er ns
A nni hi l at i ng ev i l w i t h A nt i -Pat t er ns
Leav i ng Ob jec t v i l l e
Br i dge
Bui l der
Chai n of Responsi b i l i t y
Fl y w ei ght
Int er pr et er
Medi at or
Mement o
Pr ot ot y pe
V i si t or
Intro: How to use this Book
N O TE
In this section, we answer the burning question: “So, why DID
they put that in a design patterns book?”
N O TE
All our examples are in Java, but you should be able
to understand the main concepts of the book if you
know another object-oriented language.
t hi s b ook i s f or y ou.
How does y our b r ai n k now w hat ’s i mpor t ant ? Suppose y ou’r e out
f or a day hi k e and a t i ger jumps i n f r ont of y ou, w hat happens
i nsi de y our head and b ody ?
Make it v isual. Images are far more memorable than words alone, and
make learning much more effective (up to 89% improvement in recall and
transfer studies). It also makes things more understandable. Put the words
within or near the graphics they relate to, rather than on the bottom or on
another page, and learners will be up to tw ice as likely to solve problems
related to the content.
Get the learner to think more deeply. In other words, unless you actively
flex your neurons, nothing much happens in your head. A reader has to be
motivated, engaged, curious, and inspired to solve problems, draw
conclusions, and generate new knowledge. And for that, you need
challenges, exercises, thought-provoking questions, activities that involve
both sides of the brain, and multiple senses.
Get—and keep—the reader’s attention. We’ve all had the “I really want to
learn this but I can’t stay awake past page one” experience. Your brain pays
attention to things that are out of the ordinary, interesting, strange, eye-
catching, unexpected. Learning a new, tough, technical topic doesn’t have
to be boring. Your brain will learn much more quickly if it’s not.
Touch their emotions. We now know that your ability to remember
something is largely dependent on its emotional content. You remember
what you care about. You remember when you feel something. No, we’re
not talking heart-wrenching stories about a boy and his dog. We’re talking
emotions like surprise, curiosity, fun, “what the...?”, and the feeling of “I
Rule! ” that comes when you solve a puzzle, learn something everybody
else thinks is hard, or realize you know something that “I’m more technical
than thou” Bob from engineering doesn’t.
N O TE
Cut this out and stick it on your refrigerator.
Your b r ai n w or k s b est i n a ni c e b at h of f l ui d.
Dehy dr at i on (w hi c h c an happen b ef or e y ou ev er f eel
t hi r st y ) dec r eases c ogni t i v e f unc t i on.
8. Fe e l something!
9. De s ig n something!
Read Me
Thi s i s a l ear ni ng ex per i enc e, not a r ef er enc e b ook . W e
del i b er at el y st r i pped out ev er y t hi ng t hat mi ght get i n t he w ay of
l ear ni ng w hat ev er i t i s w e’r e w or k i ng on at t hat poi nt i n t he b ook .
A nd t he f i r st t i me t hr ough, y ou need t o b egi n at t he b egi nni ng,
b ec ause t he b ook mak es assumpt i ons ab out w hat y ou’v e al r eady
seen and l ear ned.
Tech Reviewers
Tech Reviewers, 2nd Edition
Acknowledgments
At O’Re illy :
Our intre p id re v ie w e rs :
Acknowledgments
At O’Re illy :
Fi r st and f or emost , Mary Treseler i s t he super pow er w ho mak es
ev er y t hi ng happen and w e ar e et er nal l y gr at ef ul t o her f or al l she
does f or O’Rei l l y , Head Fi r st , and t he aut hor s. Melissa Duffield and
Michele Cronin c l ear ed many pat hs t hat made t hi s sec ond edi t i on
happen. Rachel Monaghan di d an amazi ng c opy edi t , gi v i ng a new
spar k l e t o our t ex t . Kristen Brown made t he b ook l ook b eaut i f ul
onl i ne and i n pr i nt . Ellie Volckhausen w or k ed her magi c and
desi gned a b r i l l i ant new c ov er f or t he sec ond edi t i on. Thank y ou
al l !
Last , a per sonal t hank y ou t o t he Jav aranch rev iew team f or t hei r
t op-not c h r ev i ew s and w ar m suppor t . Ther e’s mor e of y ou i n t hi s
b ook t han y ou k now .
What happened?
Joe f ai l ed t o not i c e t hat not all sub c l asses of Duc k shoul d fly . W hen
Joe added new b ehav i or t o t he Duc k super c l ass, he w as al so addi ng
b ehav i or t hat w as not appr opr i at e f or some Duc k sub c l asses. He
now has f l y i ng i nani mat e ob jec t s i n t he Si mU Duc k pr ogr am.
A loc aliz ed update to th e c ode c aus ed a non-loc al s ide effec t (fly ing
rubber duc k s )!
W h a t Jo e th o ug h t w a s a g re a t us e o f inh e rita nce fo r
th e p urp o s e o f re us e h a s n’t turne d o ut s o w e ll w h e n it
co m e s to m a inte na nce .
SH AR PEN YO U R PEN C IL
Which of the following are disadvantages of using inheritance to provide
Duck behavior? (Choose all that apply.)
My customers or users decide they want something else, or they want new
functionality.
____________________________________________________________
_________
____________________________________________________________
_________
____________________________________________________________
_________
____________________________________________________________
_________
____________________________________________________________
_________
SH AR PEN YO U R PEN C IL
1. Using our new design, what would you do if you needed to add
rocket-powered flying to the SimUDuck app?
2. Can you think of a class that might want to use the Quack
behavior that isn’t a duck?
A nsw er s:
N O TE
Here’s the key: A Duck will now delegate its flying and
quacking behaviors, instead of using quacking and
flying methods defined in the Duck class (or subclass).
Here’s how:
More integration...
5. Run it!
N O TE
Make sure you do this.
B R AIN PO W ER
A duck call is a device that hunters use to mimic the calls (quacks) of
ducks. How would you implement your own duck call that does not inherit
from the Duck class?
G U R U AN D ST U D EN T
Guru: Continue...
Student: Guru, through inheritance all good things may be reused and so
w e come to drastically cut development time like w e sw iftly cut bamboo in
the w oods.
Student: The answ er is after, Guru. We alw ays spend more time
maintaining and changing softw are than on initial development.
Guru: I can see that you still have much to learn. I w ould like for you to go
and meditate on inheritance further. As you’ve seen, inheritance has its
problems, and there are other w ays of achieving reuse.
N O TE
The Strategy Pattern defines a family of algorithms,
encapsulates each one, and makes them interchangeable.
Strategy lets the algorithm vary independently from clients that
use it.
N O TE
Use THIS definition when you need to impress friends and
influence key executives.
Design Puzzle
Bel ow y ou’l l f i nd a mess of c l asses and i nt er f ac es f or an ac t i on
adv ent ur e game. You’l l f i nd c l asses f or game c har ac t er s al ong w i t h
c l asses f or w eapon b ehav i or s t he c har ac t er s c an use i n t he game.
Eac h c har ac t er c an mak e use of one w eapon at a t i me, b ut c an
c hange w eapons at any t i me dur i ng t he game. Your job i s t o sor t i t
al l out ...
Y our task:
1 . A r r ange t he c l asses.
3. Dr aw ar r ow s b et w een c l asses.
c . Dr aw t hi s k i nd of ar r ow f or HA S-A .
Can you think of aspects of OO design that get communicated along with
pattern names? What qualities get communicated along with the name
“Strategy Pattern”?
N O TE
“We’re using the Strategy Pattern to implement the various
behaviors of our ducks.” This tells you the duck behavior has
been encapsulated into its own set of classes that can be easily
expanded and changed, even at runtime if needed.
N O TE
How many design meetings have you been in that quickly
degrade into implementation details?
N O TE
Think about starting a patterns study group at your
organization. Maybe you can even get paid while you’re
learning...
Dev eloper: N o?
Patterns don’t give you code, they give you general solutions to
design problems. You apply them to your specific application.
ACROSS
4. St r at egi es c an b e __________.
DOWN
1 1 . Gr i l l ed c heese w i t h b ac on.
1 3. Ri c k w as t hr i l l ed w i t h t hi s pat t er n.
N O TE
Note that ANY object could implement the WeaponBehavior
interface—say, a paper clip, a tube of toothpaste, or a mutated
sea bass.
SH AR PEN YO U R PEN C IL
SO L U T IO N
Which of the following are disadvantages of using subclassing to provide
specific Duck behavior? (Choose all that apply.) Here’s our solution.
My customers or users decide they want something else, or they want new
functionality.
Well, technology changes and we’ve got to update our code to make use of
protocols.
We’ve learned enough building our system that we’d like to go back and do
things a little better.
Congratulations!
Our Goal
W e k now w e need t o i mpl ement a di spl ay and t hen hav e t he
W eat her Dat a updat e t hat di spl ay eac h t i me i t has new v al ues, or , i n
ot her w or ds, eac h t i me t he measur ement sChanged() met hod i s
c al l ed. But how ? Let ’s t hi nk t hr ough w hat w e’r e t r y i ng t o ac hei v e:
4. Subj ect
5. Meanw hi l e, f or Lor i and Ji l l l i f e goes on; i f a Jav a job
c omes al ong, t hey ’l l get not i f i ed. A f t er al l , t hey ar e
ob ser v er s.
6. Subj ect
7 . Observ er
8. Observ er
9. Subj ect
N O TE
The Observer Pattern defines a one-to-many dependency
between objects so that when one object changes state, all of its
dependents are notified and updated automatically.
W h e n th e s ta te o f o ne o b je ct ch a ng e s , a ll o f its
d e p e nd e nts a re no tifie d .
Guru: And in our softw are, might our designs break less easily if our
objects are less tightly bound together?
Student: Guru, I see the truth of it. But w hat does it mean for objects to be
less tightly bound?
Student: Ah!
Guru: Think of nature; all living things depend on each other. Likew ise, all
objects depend on other objects. But a loosely coupled object doesn’t
know or care too much about the details of another object.
Student: But Guru, that doesn’t sound like a good quality. Surely not
know ing is w orse than know ing.
Guru: You are doing w ell in your studies, but you have much to learn. By
not know ing too much about other objects, w e can create designs that can
handle change better. Designs that have more flexibility, like the less
tightly w oven basket.
N O TE
How many different kinds of change can you identify here?
Lo o s e ly co up le d d e s ig ns a llo w us to b uild fle xib le OO
s y s te m s th a t ca n h a nd le ch a ng e b e ca us e th e y
m inim ize th e inte rd e p e nd e ncy b e tw e e n o b je cts .
SH AR PEN YO U R PEN C IL
Before moving on, try sketching out the classes you’ll need to implement
the Weather Station, including the WeatherData class and its display
elements. Make sure your diagram shows how all the pieces fit together
and also how another developer might implement her own display element.
If you need a little help, read the next page; your teammates are already
talking about how to design the Weather Station.
Cubicle conversation
Bac k t o t he W eat her St at i on pr ojec t . Your t eammat es hav e al r eady
b egun t hi nk i ng t hr ough t he pr ob l em...
Sue: Li k e w hat ?
B R AIN PO W ER
Mary and Sue thought that passing the measurements directly to the
observers was the most straightforward method of updating state. Do you
think this is wise? Hint: is this an area of the application that might change
in the future? If it did change, would the change be well encapsulated, or
would it require changes in many parts of the code?
Can you think of other ways to approach the problem of passing the
updated state to the observers?
Don’t worry; we’ll come back to this design decision after we finish the
initial implementation.
SH AR PEN YO U R PEN C IL
Johnny Hurricane, Weather-O-Rama’s CEO, just called and they can’t
possibly ship without a Heat Index display element. Here are the details.
So get typing!
Just kidding. Don’t worry, you won’t have to type that formula in; just create
your own HeatIndexDisplay.java file and copy the formula from
heatindex.txt into it.
N OT E
You can get heatindex.txt from wickedlysmart.com
(http://wic k edly s mart.c om) .
How does it work? You’d have to refer to Head First Meteorology, or try
asking someone at the National Weather Service (or try a web search).
Toni ght ’s t al k : Subj ect and Observ er spar ov er the right way to
get state information to the Observ er.
Subj ect: Observ er:
Okay, wait just a minute here; first, we’re not lazy, we just
have other stuff to do in between your ohso-important
notifications, Mr. Subject, and second, why don’t you let
us come to you for the state we want rather than pushing
it out to just everyone?
Why don’t you just write some public getter methods that
will let us pull out the state we need?
Indeed.
N OT E
Lambda expressions were added in Java 8. If you aren’t familiar with
them, don’t worry about it; you can continue using inner classes for your
Swing observers.
Later, when the button is clicked, the button object notifies its observers—
including the function objects created by the lambda expressions—that it’s
been clicked, and calls each listener’s actionPerformed() method.
N OT E
For more on lambda expressions, check out the Java docs.
Code Magnets
B U L L ET PO IN T S
You can push or pull data from the Subject when using the
pattern (pull is considered more “correct”).
ACROSS
DOWN
5. He say s y ou shoul d go f or i t .
SH AR PEN YO U R PEN C IL
SO L U T IO N
Based on our first implementation, which of the following apply? (Choose
all that apply.)
W hen t hey f i r st w ent i nt o b usi ness t hey desi gned t hei r c l asses l i k e
t hi s...
}
}
public class DarkRoast extends Beverage {
public DarkRoast() {
description = “Most Excellent Dark Roast”;
}
public double cost() {
}
}
SH AR PEN YO U R PEN C IL
What requirements or other factors might change that will impact this
design?
G U R U AN D ST U D EN T
Guru: It has been some time since our last meeting. Have you been deep
in meditation on inheritance?
Student: Yes, Guru. While inheritance is pow erful, I have learned that it
doesn’t alw ays lead to the most flexible or maintainable designs.
Guru: Ah yes, you have made some progress. So, tell me, my student, how
then w ill you achieve reuse if not through inheritance?
Guru: Very good; you are beginning to see the pow er of composition.
Guru: Very good. Enough for today. I w ould like for you to go and meditate
further on this topic... Remember, code should be closed (to change) like
the lotus flow er in the evening, yet open (to extension) like the lotus
flow er in the morning.
Be ca re ful w h e n ch o o s ing th e a re a s o f co d e th a t ne e d
to b e e xte nd e d ; a p p ly ing th e Op e n-Clo s e d Princip le
EVERYW HERE is w a s te ful a nd unne ce s s a ry , a nd ca n
le a d to co m p le x, h a rd -to -und e rs ta nd co d e .
So, her e’s w hat w e’l l do i nst ead: w e’l l st ar t w i t h a b ev er age and
“dec or at e” i t w i t h t he c ondi ment s at r unt i me. For ex ampl e, i f t he
c ust omer w ant s a Dar k Roast w i t h Moc ha and W hi p, t hen w e’l l :
1 . Start with a DarkRoast obj ect.
N O TE
Key point!
N O TE
The Decorator Pattern attaches additional responsibilities to
an object dynamically. Decorators provide a flexible alternative
to subclassing for extending functionality.
B R AIN PO W ER
Before going further, think about how you’d implement the cost() method of
the coffees and the condiments. Also think about how you’d implement the
getDescription() method of the condiments.
Cubicle Conversation
Some confusion ov er I nheritance v ersus Composition
Sue: Ex ac t l y .
SH AR PEN YO U R PEN C IL
Draw your picture here.
Writing the Starbuzz code
Let’s start with the Bev erage class, which doesn’t need to
change from Starbuzz’s original design. Let’s take a look:
Coding beverages
Now that we’v e got our base classes out of the way , let’s
implement some bev erages. We’ll start with Espresso.
Remember, we need to set a description for the specific
bev erage and also implement the cost() method.
N O TE
You can create the other two Beverage classses (DarkRoast and
Decaf) in exactly the same way.
Coding condiments
I f y ou look back at the Decorator Pattern class diagram, y ou’ll
see we’v e now written our abstract component (Bev erage), we
hav e our concrete components (HouseBlend), and we hav e our
abstract decorator (CondimentDecorator). Now it’s time to
implement the concrete decorators. Here’s Mocha:
N O TE
On the next page we’ll actually instantiate the beverage and
wrap it with all its condiments (decorators), but first...
EXER C ISE
Write and compile the code for the other Soy and Whip condiments. You’ll
need them to finish and test the application.
N O TE
*We’re going to see a much better way of creating decorated
objects when we cover the Factory and Builder Design Patterns.
Please note that the Builder Pattern is covered in the Appendix.
SH AR PEN YO U R PEN C IL
Our friends at Starbuzz have introduced sizes to their menu. You can now
order a coffee in tall, grande, and venti sizes (translation: small, medium,
and large). Starbuzz saw this as an intrinsic part of the coffee class, so
they’ve added two methods to the Beverage class: setSize() and getSize().
T hey’d also like for the condiments to be charged according to size, so for
instance, Soy costs 10¢, 15¢, and 20¢, respectively, for tall, grande, and
venti coffees. T he updated Beverage class is shown below.
How would you alter the decorator classes to handle this change in
requirements?
You’l l see t hat t he output st r eams hav e t he same desi gn. A nd y ou’v e
pr ob ab l y al r eady f ound t hat t he Reader /W r i t er st r eams (f or
c har ac t er -b ased dat a) c l osel y mi r r or t he desi gn of t he st r eams
c l asses (w i t h a f ew di f f er enc es and i nc onsi st enc i es, b ut c l ose
enough t o f i gur e out w hat ’s goi ng on).
Giv e it a spin:
Head First: Welcome, Decorator Pattern. We’ve heard that you’ve been a
bit down on yourself lately?
HeadFirst: Can you perhaps share some of your troubles with us?
Decorator: Sure. Well, you know I’ve got the power to add flexibility to
designs, that much is for sure, but I also have a dark side. You see, I can
sometimes add a lot of small classes to a design, and this occasionally
results in a design that’s less than straightforward for others to understand.
Decorator: Take the Java I/O libraries. T hese are notoriously difficult for
people to understand at first. But if they just saw the classes as a set of
wrappers around an InputStream, life would be much easier.
HeadFirst: T hat doesn’t sound so bad. You’re still a great pattern, and
improving this is just a matter of public education, right?
Decorator: T here’s more, I’m afraid. I’ve got typing problems: you see,
people sometimes take a piece of client code that relies on specific types
and introduce decorators without thinking through everything. Now, one
great thing about me is that you can usually insert decorators
transparently and the client never has to know it’s dealing w ith a
decorator. But like I said, some code is dependent on specific types and
when you start introducing decorators, boom! Bad things happen.
Decorator: I know, I try not to be. I also have the problem that introducing
decorators can increase the complexity of the code needed to instantiate
the component. Once you’ve got decorators, you’ve got to not only
instantiate the component, but also wrap it with who knows how many
decorators.
HeadFirst: I’ll be interviewing the Factory and Builder patterns next week—I
hear they can be very helpful with this?
HeadFirst: Well, we all think you’re a great pattern for creating flexible
designs and staying true to the Open-Closed Principle, so keep your chin
up and think positively!
SH AR PEN YO U R PEN C IL
SO L U T IO N
Write the cost() methods for the following classes (pseudo-Java is okay).
Here’s our solution:
public DarkRoast() {
description = “Most Excellent Dark Roast”;
}
SH AR PEN YO U R PEN C IL
SO L U T IO N
Our friends at Starbuzz have introduced sizes to their menu. You can now
order a coffee in tall, grande, and venti sizes (translation: small, medium,
and large). Starbuzz saw this as an intrinsic part of the coffee class, so
they’ve added two methods to the Beverage class: setSize() and getSize().
T hey’d also like for the condiments to be charged according to size, so for
instance, Soy costs 10¢, 15¢, and 20¢, respectively, for tall, grande, and
venti coffees.
How would you alter the decorator classes to handle this change in
requirements? Here’s our solution.
Chapter 4. Baking with OO
Goodness: The Factory Pattern
N O TE
Remember that designs should be “open for extension but
closed for modification.” See Chapter 3 for a review.
B R AIN PO W ER
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?
So t hen y ou’d add some c ode t hat determ ines t he appr opr i at e t y pe of
pi zza and t hen goes ab out m ak ing t he pi zza:
N OT E
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).
N O TE
*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 abstract class OR interface) is still
considered to be “implementing the interface” of that
supertype.
N O TE
Yes, different areas of the US serve very different styles of pizza
—from the deep-dish pizzas of Chicago, to the thin crust of
New York, to the cracker-like pizza of California (some would
say topped with fruits and nuts).
W hen or der Pi zza() c al l s c r eat ePi zza(), one of y our sub c l asses w i l l
b e c al l ed i nt o ac t i on t o c r eat e a pi zza. W hi c h k i nd of pi zza w i l l b e
made? W el l , t hat ’s dec i ded b y t he c hoi c e of pi zza st or e y ou or der
f r om, N YSt y l ePi zzaSt or e or Chi c agoSt y l ePi zzaSt or e.
N O TE
* 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!
SH AR PEN YO U R PEN C IL
We’ve knocked out the NYPizzaStore; just two more to go and we’ll be
ready to franchise! Write the Chicago-style and California-style PizzaStore
implementations here:
C O D E U P C L O SE
A factory method handles object creation and encapsulates it in a
subclass. T his decouples the client code in the superclass from the
object creation code in the subclass.
Let’s see how it works: ordering pizzas with the pizza factory
method
Let’s check out how these pizzas are really made to order...
We’re just missing one thing: Pizzas!
N O TE
REMEMBER: we don’t provide import and package statements
in the code listings. Get the complete source code from the
wickedlysmart website at https://wickedlysmart.com/head-
first-design-patterns
If you lose this URL, you can always quickly find it in the Intro
section.
Design Puzzle
W e need anot her k i nd of pi zza f or t hose c r azy Cal i f or ni ans (c r azy
i n a good w ay , of c our se). Dr aw anot her par al l el set of c l asses t hat
y ou’d need t o add a new Cal i f or ni a r egi on t o our Pi zzaSt or e.
__________________________________________________
___________
__________________________________________________
___________
__________________________________________________
___________
__________________________________________________
___________
__________________________________________________
___________
N O TE
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.
N O TE
You could ask them what “decides” means, but we bet you now
understand this better than they do!
A: The Fac t or y Met hod Pat t er n i s usef ul i f y ou’v e onl y got one
c onc r et e c r eat or b ec ause y ou ar e dec oupl i ng t he i mpl ement at i on
of t he pr oduc t f r om i t s use. If y ou add addi t i onal pr oduc t s or c hange
a pr oduc t ’s i mpl ement at i on, i t w i l l not af f ec t y our Cr eat or
(b ec ause t he Cr eat or i s not t i ght l y c oupl ed t o any
Conc r et ePr oduc t ).
Guru: Go on...
S tud e nt: Th ere are m any . By plac ing all m y c reation c ode in one
objec t or m eth od, I av oid duplic ation in m y c ode and prov ide one
plac e to perform m aintenanc e. Th at als o m eans c lients depend only
upon interfac es rath er th an th e c onc rete c las s es req uired to
ins tantiate objec ts . As I h av e learned in m y s tudies , th is allow s m e
to program to an interfac e, not an im plem entation, and th at m ak es
m y c ode m ore flexible and extens ible in th e future.
SH AR PEN YO U R PEN C IL
Let’s pretend you’ve never heard of an OO factory. Here’s a “very dependent”
version of PizzaStore that doesn’t use a factory. We need you to make a
count of the number of concrete pizza classes this class is dependent on.
If you added California-style pizzas to this PizzaStore, how many classes
would it be dependent on then?
N O TE
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.
N O TE
A “high-level” component is a class with behavior defined in
terms of other, “low-level” components.
How c an w e get t hose i nst ant i at i ons out of t he or der Pi zza() met hod?
W el l , as w e k now , t he Fac t or y Met hod Pat t er n al l ow s us t o do just
t hat .
N O TE
If you use new, you’ll be holding a reference to a
concrete class. Use a factory to get around that!
N O TE
But wait, aren’t these guidelines impossible to
follow? If I follow these, I’ll never be able to write a
single program!
N O TE
That is, the baking, the cutting, the boxing, and so on...
Families of ingredients...
N ew Yor k uses one set of i ngr edi ent s and Chi c ago anot her . Gi v en
t he popul ar i t y of Ob jec t v i l l e Pi zza, i t w on’t b e l ong b ef or e y ou al so
need t o shi p anot her set of r egi onal i ngr edi ent s t o Cal i f or ni a, and
w hat ’s nex t ? A ust i n?
N O TE
In total, these three regions make up ingredient families, with
each region implementing a complete family of ingredients.
SH AR PEN YO U R PEN C IL
Write the ChicagoPizzaIngredientFactory. You can reference the classes
below in your implementation:
So, w hat y ou’l l see i s t hat w e r eal l y don’t need t w o c l asses f or eac h
pi zza; t he i ngr edi ent f ac t or y i s goi ng t o handl e t he r egi onal
di f f er enc es f or us.
C O D E U P C L O SE
T he Pizza code uses the factory it has been composed with to produce the
ingredients used in the pizza. T he ingredients produced depend on which
factory we’re using. T he Pizza class doesn’t care; it knows how to make
pizzas. Now, it’s decoupled from the differences in regional ingredients
and can be easily reused when there are factories for the Austin, the
Nashville, and beyond.
B R AIN PO W ER
Compare this version of the createPizza() method to the one in the Factory
Method implementation earlier in the chapter.
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...
N O TE
The Abstract Factory Pattern provides an interface for
creating families of related or dependent objects without
specifying their concrete classes.
HeadFirst: Wow, an interview with two patterns at once! T his is a first for
us.
Factory Method: Yeah, I’m not so sure I like being lumped in with Abstract
Factory, you know. Just because we’re both factory patterns doesn’t mean
we shouldn’t get our own interviews.
Abstract Factory: It’s true, there have been times I’ve been mistaken for
Factory Method, and I know you’ve had similar issues, Factory Method.
We’re both really good at decoupling applications from specific
implementations; we just do it in different ways. So I can see why people
might sometimes get us confused.
Factory Method: Well, it still ticks me off. After all, I use classes to create
and you use objects; that’s totally different!
HeadFirst: Oh, I see, so another advantage is that you group together a set
of related products.
HeadFirst: What happens if you need to extend that set of related products
to, say, add another one? Doesn’t that require changing your interface?
Factory Method: Oh, come on, that’s a big deal! Changing your interface
means you have to go in and change the interface of every subclass! T hat
sounds like a lot of work.
HeadFirst: Abstract Factory, I heard that you often use factory methods to
implement your concrete factories?
Abstract Factory: Yes, I’ll admit it, my concrete factories often implement
a factory method to create their products. In my case, they are used purely
to create products...
HeadFirst: It sounds like you both are good at what you do. I’m sure people
like having a choice; after all, factories are so useful, they’ll want to use
them in all kinds of different situations. You both encapsulate object
creation to keep applications loosely coupled and less dependent on
implementations, which is really great, whether you’re using Factory
Method or Abstract Factory. May I allow you each a parting word?
Factory Method: And I’m Factory Method; use me to decouple your client
code from the concrete classes you need to instantiate, or if you don’t
know ahead of time all the concrete classes you are going to need. To use
me, just subclass me and implement my factory method!
ACROSS
1 2. Joel l i k es t hi s k i nd of pi zza.
1 3. In Fac t or y Met hod, t he Pi zzaSt or e and t he c onc r et e Pi zzas al l
depend on t hi s ab st r ac t i on.
DOWN
1 0. Et han l i k es t hi s k i nd of pi zza.
SH AR PEN YO U R PEN C IL
SO L U T IO N
We’ve knocked out the NYPizzaStore; just two more to go and we’ll be
ready to franchise! Write the Chicago-style and California-style PizzaStore
implementations here:
SH AR PEN YO U R PEN C IL
SO L U T IO N
Go ahead and write the ChicagoPizzaIngredientFactory; you can reference
the classes below in your implementation:
Our next stop is the Singleton Pattern, our ticket to creating one-
of-a-kind obj ects for which there is only one instance, ev er. You
mi ght b e happy t o k now t hat of al l pat t er ns, t he Si ngl et on i s t he
si mpl est i n t er ms of i t s c l ass di agr am; i n f ac t , t he di agr am hol ds just
a si ngl e c l ass! But don’t get t oo c omf or t ab l e; despi t e i t s si mpl i c i t y
f r om a c l ass desi gn per spec t i v e, i t ’s goi ng t o r equi r e some deep
ob jec t -or i ent ed t hi nk i ng i n i t s i mpl ement at i on. So put on t hat
t hi nk i ng c ap, and l et ’s get goi ng.
De v e lo p e r: Wh at us e is th at?
Guru: Th ere are m any objec ts w e only need one of: th read pools ,
c ac h es , dialog boxes , objec ts th at h andle preferenc es and regis try
s ettings , objec ts us ed for logging, and objec ts th at ac t as dev ic e
driv ers to dev ic es lik e printers and graph ic s c ards . I n fac t, for
m any of th es e ty pes of objec ts , if w e w ere to ins tantiate m ore th an
one w e’d run into all s orts of problem s lik e inc orrec t program
beh av ior, ov erus e of res ourc es , or inc ons is tent res ults .
De v e lo p e r: Wh at dow ns ides ?
And if not? Well, if it’s not a public class, only classes in the same package can
instantiate it. But they can still instantiate it more than once.
Hmm, No, I’d never thought of it, but I guess it makes sense because it is a
interesting. legal definition.
Did you know
you could do
this?
public
MyClass
{
private
MyClass
() {}
Well, is there Hmm, I think the code in MyClass is the only code that could call it.
ANY object that But that doesn’t make much sense.
could use the
private
constructor?
Why not ? Because I’d have to have an instance of the class to call it, but I
can’t have an instance because no other class can instantiate it. It’s
a chicken-and-egg problem: I can use the constructor from an
object of type MyClass, but I can never instantiate that object
because no other object can use “new MyClass()”.
public
MyClass
{
public
static
MyClass
getInst
ance()
{
}
}
Why did you use Well, getInstance() is a static method; in other words, it is a CLASS
MyClass instead method. You need to use the class name to reference a static method.
of some object
name?
public
MyClass
{
private
MyClass
() {}
public
static
MyClass
getInst
ance()
{
return
new
MyClass
();
}
}
HeadFirst: One?
Singleton: Yes, one. I’m based on the Singleton Pattern, which ensures
that at any time there is only one instance of me.
HeadFirst: Isn’t that sort of a waste? Someone took the time to develop a
full-blown class and now all we can get is one object out of it?
Singleton: Not at all! T here is power in ONE. Let’s say you have an object
that contains registry settings. You don’t want multiple copies of that
object and its values running around—that would lead to chaos. By using
an object like me you can ensure that every object in your application is
making use of the same global resource.
Singleton: Oh, I’m good for all kinds of things. Being single sometimes
has its advantages, you know. I’m often used to manage pools of
resources, like connection or thread pools.
Singleton: Because there’s only one of me, I do keep busy, but it would be
nice if more developers knew me—many developers run into bugs because
they have multiple copies of objects floating around they’re not even aware
of.
HeadFirst: So, if we may ask, how do you know there is only one of you?
Can’t anyone with a new operator create a “new you”?
HeadFirst: How does that work? How do you EVER get instantiated?
HeadFirst: Well, Mr. Singleton, there seems to be a lot under your covers
to make all this work. T hanks for revealing yourself and we hope to speak
with you again soon!
B R AIN PO W ER
Choc-O-Holic has done a decent job of ensuring bad things don’t happen,
don’t you think? T hen again, you probably suspect that if two
ChocolateBoiler instances get loose, some very bad things can happen.
SH AR PEN YO U R PEN C IL
Can you help Choc-O-Holic improve their ChocolateBoiler class by turning
it into a Singleton?
N O TE
The Singleton Pattern ensures a class has only one instance,
and provides a global point of access to it.
No big surprises there. But let’s break it down a bit more:
Could the addition of threads hav e caused this? I sn’t it the case
that once we’v e set the uniqueI nstance v ariable to the sole
instance of ChocolateBoiler, all calls to getI nstance() should
return the same instance? Right?
BE the JVM
That ’s r i ght ; i f c al l i ng t he get Inst anc e() met hod i sn’t c ausi ng
sub st ant i al ov er head f or y our appl i c at i on, f or get ab out i t .
Sy nc hr oni zi ng get Inst anc e() i s st r ai ght f or w ar d and ef f ec t i v e. Just
k eep i n mi nd t hat sy nc hr oni zi ng a met hod c an dec r ease
per f or manc e b y a f ac t or of 1 00, so i f a hi gh-t r af f i c par t of y our
c ode b egi ns usi ng get Inst anc e(), y ou may hav e t o r ec onsi der .
If per f or manc e i s an i ssue i n y our use of t he get Inst anc e() met hod,
t hen t hi s met hod of i mpl ement i ng t he Si ngl et on c an dr ast i c al l y
r educ e t he ov er head.
W AT C H IT !
Double-checked locking doesn’t work in Jav a 1.4 or earlier!
____________________________________________________________
___
____________________________________________________________
___
____________________________________________________________
___
____________________________________________________________
___
Double-checked locking:
____________________________________________________________
___
____________________________________________________________
___
Congratulations!
A t t hi s poi nt , t he Choc ol at e Fac t or y i s a happy c ust omer and Choc -
O-Hol i c w as gl ad t o hav e some ex per t i se appl i ed t o t hei r b oi l er
c ode. N o mat t er w hi c h mul t i t hr eadi ng sol ut i on y ou appl i ed, t he
b oi l er shoul d b e i n good shape w i t h no mor e mi shaps.
Congr at ul at i ons—not onl y hav e y ou managed t o esc ape 500 l b s of
hot c hoc ol at e i n t hi s c hapt er , b ut y ou’v e al so b een t hr ough al l t he
pot ent i al pr ob l ems of t he Si ngl et on Pat t er n.
A: Yes, i f y our c l ass i s sel f -c ont ai ned and doesn’t depend on c ompl ex
i ni t i al i zat i on. How ev er , b ec ause of t he w ay st at i c i ni t i al i zat i ons
ar e handl ed i n Jav a, t hi s c an get v er y messy , espec i al l y i f mul t i pl e
c l asses ar e i nv ol v ed. Of t en t hi s sc enar i o c an r esul t i n sub t l e, har d-
t o-f i nd b ugs i nv ol v i ng or der of i ni t i al i zat i on. U nl ess t her e i s a
c ompel l i ng need t o i mpl ement y our “si ngl et on” t hi s w ay , i t ’s f ar
b et t er t o st ay i n t he ob jec t w or l d.
N O TE
And back in the old days, when we had to walk to school, uphill,
in the snow, in both directions, Java didn’t have enums.
B R AIN PO W ER
Can you rework Choc-O-Holic to use an enum? Give it a try.
N O TE
As you’ve seen, despite its apparent simplicity, there are a lot of
details involved in Singleton’s implementation. After reading
this chapter, though, you’re ready to go out and use Singleton
in the wild.
B U L L ET PO IN T S
DOWN
1 . A dded t o c hoc ol at e i n t he b oi l er .
3. It w as “one of a k i nd.”
9. Choc ol at e c api t al of t he U SA .
B E T H E JVM SO L U T IO N
SH AR PEN YO U R PEN C IL
SO L U T IO N
Can you help Choc-O-Holic improve their ChocolateBoiler class by turning
it into a Singleton?
SH AR PEN YO U R PEN C IL
SO L U T IO N
For each solution, describe its applicability to the problem of fixing the
Chocolate Boiler code:
the instance would cause no concerns. T his solution would work as well
as the synchronized
Double-checked locking:
Cubicle Conversation
Your t eammat es ar e al r eady di sc ussi ng how t o desi gn t he r emot e
c ont r ol A PI...
Sue: But i f t he r emot e i s dumb and just k now s how t o mak e gener i c
r equest s, how do w e desi gn t he r emot e so t hat i t c an i nv ok e an
ac t i on t hat , say , t ur ns on a l i ght or opens a gar age door ?
Sue: I agr ee. W henev er a new v endor c l ass c omes out , w e’d hav e t o
go i n and modi f y t he c ode, pot ent i al l y c r eat i ng b ugs and mor e w or k
f or our sel v es!
Mary : Yeah? Tel l us mor e.
Sue: Me t oo.
The Short-Order Cook is the obj ect that really knows how to
prepare meals. Onc e t he W ai t r ess has i nv ok ed t he or der U p()
met hod; t he Shor t -Or der Cook t ak es ov er and i mpl ement s al l t he
met hods t hat ar e needed t o c r eat e meal s. N ot i c e t he W ai t r ess and
t he Cook ar e t ot al l y dec oupl ed: t he W ai t r ess has Or der Sl i ps t hat
enc apsul at e t he det ai l s of t he meal ; she just c al l s a met hod on eac h
Or der t o get i t pr epar ed. Li k ew i se, t he Cook get s hi s i nst r uc t i ons
f r om t he Or der Sl i p; he nev er needs t o di r ec t l y c ommuni c at e w i t h
t he W ai t r ess.
W H O D O ES W H AT ?
Match the diner objects and methods with the corresponding names from
the Command Pattern.
Waitress Command
orderUp() Client
Order Invoker
Customer Receiver
takeOrder() setCommand()
Now that you’ve got your class, what is the output of the following code?
(Hint: the GarageDoor up() method prints out “Garage Door is Open” when it
is complete.)
remote.setCommand(lightOn);
remote.buttonWasPressed();
remote.setCommand(garageOpen);
remote.buttonWasPressed();
}
}
N O TE
The Command Pattern encapsulates a request as an object,
thereby letting you parameterize other objects with different
requests, queue or log requests, and support undoable
operations.
Let ’s st ep t hr ough t hi s. W e k now t hat a c ommand ob jec t
enc aps ulates a req ues t b y b i ndi ng t oget her a set of ac t i ons on a
spec i f i c r ec ei v er . To ac hi ev e t hi s, i t pac k ages t he ac t i ons and t he
r ec ei v er i nt o an ob jec t t hat ex poses just one met hod, ex ec ut e().
W hen c al l ed, ex ec ut e() c auses t he ac t i ons t o b e i nv ok ed on t he
r ec ei v er . Fr om t he out si de, no ot her ob jec t s r eal l y k now w hat
ac t i ons get per f or med on w hat r ec ei v er ; t hey just k now t hat i f t hey
c al l t he ex ec ut e() met hod, t hei r r equest w i l l b e ser v i c ed.
B R AIN PO W ER
How does the design of the Command Pattern support the decoupling of
the invoker of a request and the receiver of the request?
Mary : Me t oo. So w her e do w e b egi n?
onCommands[0] = onCommand;
offCommands[0] = offCommand;
So, how do w e get ar ound t hat ? Impl ement a c ommand t hat does
not hi ng!
So, i n t he out put of our t est r un, y ou’r e seei ng onl y sl ot s t hat hav e
b een assi gned t o a c ommand ot her t han t he def aul t N oCommand
ob jec t , w hi c h w e assi gned w hen w e c r eat ed t he Remot eCont r ol
c onst r uc t or .
PAT T ER N H O N O R AB L E
M EN T IO N
T he NoCommand object is an example of a null object. A null object is
useful when you don’t have a meaningful object to return, and yet you want
to remove the responsibility for handling null from the client. For instance,
in our remote control we didn’t have a meaningful object to assign to each
slot out of the box, so we provided a NoCommand object that acts as a
surrogate and does nothing when its execute() method is called.
You’ll find uses for Null Objects in conjunction with many Design Patterns,
and sometimes you’ll even see “Null Object” listed as a Design Pattern.
Note that you can only do this if your Command interface has one abstract
method. As soon as we add a second abstract method, the lambda
shorthand no longer works.
If you like this technique, check out your favorite Java reference for more
information on the lambda expression.
SH AR PEN YO U R PEN C IL
We’ll also need commands for the off buttons. Write the
code to create those here:
B R AIN PO W ER
How might a web server make use of such a queue? What other
applications can you think of?
SH AR PEN YO U R PEN C IL
Here’s the code (the important bits anyway) for the little life-changing
application from Chapter 2. See if you can identify who is the Client, who
are the Commands, who is the Invoker, and who is the Receiver.
SH AR PEN YO U R PEN C IL
SO L U T IO N
Here’s the code (the important bits anyway) for the little life-changing
application from Chapter 2. See if you can identify who is the Client, who
are the Commands, who is the Invoker, and who is the Receiver.
B U L L ET PO IN T S
ACROSS
5. Our f av or i t e c i t y .
DOWN
1 1 . A l l c ommands pr ov i de t hi s.
W H O D O ES W H AT SO L U T IO N ?
Match the diner objects and methods with the corresponding names from
the Command Pattern.
SH AR PEN YO U R PEN C IL
SO L U T IO N
Here’s the code for the GarageDoorOpenCommand class.
EXER C ISE SO L U T IO N
Here is the undo() method for the MacroCommand.
N O TE
How many other real-world adapters can you think of?
Object-oriented adapters
Say y ou’v e got an ex i st i ng sof t w ar e sy st em t hat y ou need t o w or k a
new v endor c l ass l i b r ar y i nt o, b ut t he new v endor desi gned t hei r
i nt er f ac es di f f er ent l y t han t he l ast v endor :
Ok ay , y ou don’t w ant t o sol v e t he pr ob l em b y c hangi ng y our
ex i st i ng c ode (and y ou c an’t c hange t he v endor ’s c ode). So w hat do
y ou do? W el l , y ou c an w r i t e a c l ass t hat adapt s t he new v endor
i nt er f ac e i nt o t he one y ou’r e ex pec t i ng.
N O TE
Can you think of a solution that doesn’t require YOU to write
ANY additional code to integrate the new vendor classes? How
about making the vendor supply the adapter class?
So, l et ’s w r i t e an A dapt er :
C O D E U P C L O SE
SH AR PEN YO U R PEN C IL
Let’s say we also need an Adapter that converts a Duck to a T urkey. Let’s
call it DuckAdapter. Write that class:
How did you handle the fly() method (after all, we know ducks fly longer than
turkeys)?
Check the answers at the end of the chapter for our solution. Did you think
of a better way?
Q: What if I hav e old and new parts of my sy stem, and the old
parts expect the old v endor interface, but we’v e already written
the new parts to use the new v endor interface? I t’s going to get
confusing using an adapter here and the unwrapped interface
there. Wouldn’t I be better off j ust writing my older code and
forgetting the adapter?
N O TE
The Adapter Pattern converts the interface of a class into
another interface the clients expect. Adapter lets classes work
together that couldn’t otherwise because of incompatible
interfaces.
B R AIN PO W ER
Object adapters and class adapters use two different means of adapting
the adaptee (composition versus inheritance). How do these
implementation differences affect the flexibility of the adapter?
Duck Magnets
Class Adapter
N O TE
Drag these onto the class diagram to show which part of the
diagram represents the Duck class and which represents the
Turkey class.
Duck Magnets Answer
N O TE
Note: the class adapter uses multiple inheritance, so you can’t
do it in Java...
Class Adapter
Toni ght ’s t al k : Obj ect Adapter and Class Adapter meet face to
face.
Object Adapter: Class Adapter:
Sounds messy...
Real-world adapters
Let ’s t ak e a l ook at t he use of a si mpl e A dapt er i n t he r eal w or l d
(somet hi ng mor e ser i ous t han Duc k s at l east )...
Enumerators
Iterators
EXER C ISE
While Java has gone in the direction of the Iterator interface, there is
nevertheless still legacy client code that depends on the Enumeration
interface, so an Adapter that converts an Iterator to an Enumeration could
potentially be useful.
B R AIN PO W ER
Some AC adapters do more than just change the interface—they add other
features like surge protection, indicator lights, and other bells and
whistles.
If you were going to implement these kinds of features, what pattern would
you use?
Toni ght ’s t al k : The Decorator Pattern and the Adapter Pattern
discuss their differences.
Decorator: Adapter:
W H O D O ES W H AT ?
Match each pattern with its intent:
Pattern Intent
Let’s check out those same tasks in terms of the classes and the
method calls needed to perform them:
But there’s more...
Q: What is the benefit of the facade other than the fact that I
now hav e a simpler interface?
Fa ca d e s a nd a d a p te rs m a y w ra p m ultip le cla s s e s ,
b ut a fa ca d e ’s inte nt is to s im p lify , w h ile a n a d a p te r’s
is to co nv e rt th e inte rfa ce to s o m e th ing d iffe re nt.
B R AIN PO W ER
T hink about the facades you’ve encountered in the Java API. Where would
you like to have a few new ones?
It ’s show t i me!
Facade Pattern defined
To use t he Fac ade Pat t er n, w e c r eat e a c l ass t hat si mpl i f i es and
uni f i es a set of mor e c ompl ex c l asses t hat b el ong t o some sub sy st em.
U nl i k e a l ot of pat t er ns, Fac ade i s f ai r l y st r ai ght f or w ar d; t her e ar e
no mi nd-b endi ng ab st r ac t i ons t o get y our head ar ound. But t hat
doesn’t mak e i t any l ess pow er f ul : t he Fac ade Pat t er n al l ow s us t o
av oi d t i ght c oupl i ng b et w een c l i ent s and sub sy st ems, and, as y ou
w i l l see shor t l y , al so hel ps us adher e t o a new ob jec t -or i ent ed
pr i nc i pl e.
N O TE
The Facade Pattern provides a unified interface to a set of
interfaces in a subsystem. Facade defines a higher-level
interface that makes the subsystem easier to use.
B R AIN PO W ER
Can you think of a common use of Java that violates the Principle of Least
Knowledge?
When you need to use an existing class and its interface is not
the one you need, use an adapter.
T here are two forms of the Adapter Pattern: object and class
adapters. Class adapters require multiple inheritance.
ACROSS
5. A n A dapt er __________ an i nt er f ac e.
1 1 . A dapt er w i t h t w o r ol es (t w o w or ds).
1 7 . A __________ si mpl i f i es an i nt er f ac e.
DOWN
SH AR PEN YO U R PEN C IL
SO L U T IO N
Let’s say we also need an Adapter that converts a Duck to a T urkey. Let’s
call it DuckAdapter. Here’s our solution:
SH AR PEN YO U R PEN C IL
SO L U T IO N
Do either of these classes violate the Principle of Least Knowledge? Why
or why not?
EXER C ISE SO L U T IO N
You’ve seen how to implement an adapter that adapts an Enumeration to
an Iterator; now write an adapter that adapts an Iterator to an Enumeration.
W H O D O ES W H AT SO L U T IO N ?
Match each pattern with its intent:
Design Patterns Crossword Solution
Chapter 8. Encapsulating
Algorithms: The Template Method
Pattern
D ESIG N PU Z Z L E
You’ve seen that the Coffee and Tea classes have a fair bit of code
duplication. Take another look at the Coffee and Tea classes and draw a
class diagram showing how you’d redesign the classes to remove
redundancy:
Abstracting prepareRecipe()
Let ’s st ep t hr ough ab st r ac t i ng pr epar eRec i pe() f r om eac h sub c l ass
(t hat i s, t he Cof f ee and Tea c l asses)...
void prepareRecipe() {
boilWater();
brew();
pourInCup();
addCondiments();
}
N O TE
(Code on the next page.)
3. Fi nal l y , w e need t o deal w i t h t he Cof f ee and Tea c l asses.
They now r el y on Caf f ei neBev er age t o handl e t he r ec i pe,
so t hey just need t o handl e b r ew i ng and c ondi ment s:
SH AR PEN YO U R PEN C IL
Draw the new class diagram now that we’ve moved the implementation of
prepareRecipe() into the CaffeineBeverage class:
Th e Te m p la te Me th o d d e fine s th e s te p s o f a n
a lg o rith m a nd a llo w s s ub cla s s e s to p ro v id e th e
im p le m e nta tio n fo r o ne o r m o re s te p s .
Coffee and Tea are running The CaffeineBeverage class runs the show; it has the
the show; they control the algorithm, and protects it.
algorithm.
Code is duplicated across The CaffeineBeverage class maximizes reuse among the
Coffee and Tea. subclasses.
Code changes to the The algorithm lives in one place and code changes only
algorithm require opening need to be made there.
the subclasses and making
multiple changes.
Classes are organized in a The Template Method Pattern provides a framework that
structure that requires a lot other caffeine beverages can be plugged into. New
of work to add a new caffeine beverages only need to implement a couple of
caffeine beverage. methods.
N O TE
The Template Method Pattern defines the skeleton of an
algorithm in a method, deferring some steps to subclasses.
Template Method lets subclasses redefine certain steps of an
algorithm without changing the algorithm’s structure.
C O D E W AY U P C L O SE
Now we’re going to look even closer at the types of method that can go in
the abstract class:
How do w e k now w het her t he c ust omer w ant s t he c ondi ment ? Just
ask !
B R AIN PO W ER
What other patterns make use of the Hollywood Principle?
W H O D O ES W H AT ?
Match each pattern with its description:
Pattern Description
B R AIN PO W ER
We know that we should favor composition over inheritance, right? Well,
the implementers of the sort() template method decided not to use
inheritance and instead to implement sort() as a static method that is
composed with a Comparable at runtime. How is this better? How is it
worse? How would you approach this problem? Do Java arrays make this
particularly tricky?
B R AIN PO W ER
T hink of another pattern that is a specialization of the template method. In
this specialization, primitive operations are used to create and return
objects. What pattern is this?
U p nex t on our Templ at e Met hod saf ar i ...k eep y our ey e out f or
sw i ngi ng JFr ames!
ACROSS
1 . Huey , Loui e, and Dew ey al l w ei gh __________ pounds.
1 3. Ty pe of sor t used i n A r r ay s.
DOWN
6. Bi g-headed pat t er n.
SH AR PEN YO U R PEN C IL
SO L U T IO N
Draw the new class diagram now that we’ve moved prepareRecipe() into
the CaffeineBeverage class:
W H O D O ES W H AT SO L U T IO N ?
Match each pattern with its description:
There are lots of way s to stuff obj ects into a collection. Put t hem
i nt o an A r r ay , a St ac k , a Li st , a hash map—t ak e y our pi c k . Eac h has
i t s ow n adv ant ages and t r adeof f s. But at some poi nt y our c l i ent s ar e
goi ng t o w ant t o i t er at e ov er t hose ob jec t s, and w hen t hey do, ar e
y ou goi ng t o show t hem y our i mpl ement at i on? W e c er t ai nl y hope
not ! That just w oul dn’t b e pr of essi onal . W el l , y ou don’t hav e t o r i sk
y our c ar eer ; i n t hi s c hapt er y ou’r e goi ng t o see how y ou c an al l ow
y our c l i ent s t o i t er at e t hr ough y our ob jec t s w i t hout ev er get t i ng a
peek at how y ou st or e y our ob jec t s. You’r e al so goi ng t o l ear n how
t o c r eat e some super c ol l ec t i ons of ob jec t s t hat c an l eap ov er some
i mpr essi v e dat a st r uc t ur es i n a si ngl e b ound. A nd i f t hat ’s not
enough, y ou’r e al so goi ng t o l ear n a t hi ng or t w o ab out ob jec t
r esponsi b i l i t y .
SH AR PEN YO U R PEN C IL
Based on our implementation of printMenu(), which of the following apply?
What now?
Mel and Lou ar e put t i ng us i n a di f f i c ul t posi t i on. They don’t w ant
t o c hange t hei r i mpl ement at i ons b ec ause i t w oul d mean r ew r i t i ng
a l ot of c ode t hat i s i n eac h r espec t i v e menu c l ass. But i f one of t hem
doesn’t gi v e i n, t hen w e’r e goi ng t o hav e t he job of i mpl ement i ng a
W ai t r ess t hat w i l l b e har d t o mai nt ai n and ex t end.
EXER C ISE
Go ahead and implement the PancakeHouseIterator yourself and make the
changes needed to incorporate it into the PancakeHouseMenu.
Hard-to-Maintain Waitress
Implementation New, Hip Waitress Powered by Iterator
The Menus are not well The Menu implementations are now encapsulated. The
encapsulated; we can see the Waitress has no idea how the Menus hold their
Diner is using an ArrayList collection of menu items.
and the Pancake House an
Array.
We need two loops to iterate All we need is a loop that polymorphically handles
through the MenuItems. any collection of items as long as it implements
Iterator.
The Waitress is bound to two The Menu interfaces are now exactly the same and, uh
different concrete Menu oh, we still don’t have a common interface, which
classes, despite their interfaces means the Waitress is still bound to two concrete
being almost identical. Menu classes. We’d better fix that.
Reviewing our current design...
Bef or e w e c l ean t hi ngs up, l et ’s get a b i r d’s-ey e v i ew of our c ur r ent
desi gn.
A: The r emov e() met hod i s c onsi der ed opt i onal . You don’t hav e t o
pr ov i de r emov e f unc t i onal i t y . But y ou shoul d pr ov i de t he met hod
b ec ause i t ’s par t of t he It er at or i nt er f ac e. If y ou’r e not goi ng t o
al l ow r emov e() i n y our i t er at or , y ou’l l w ant t o t hr ow t he r unt i me
ex c ept i on jav a.l ang.U nsuppor t edOper at i onEx c ept i on. The It er at or
A PI doc ument at i on spec i f i es t hat t hi s ex c ept i on may b e t hr ow n
f r om r emov e() and any c l i ent t hat i s a good c i t i zen w i l l c hec k f or
t hi s ex c ept i on w hen c al l i ng t he r emov e() met hod.
Q: How does remov e() behav e under multiple threads that may
be using different iterators ov er the same collection of obj ects?
N O TE
This solves the problem of the Waitress depending on the
concrete Menus.
A l so, t he new Menu i nt er f ac e has one met hod, c r eat eIt er at or (), t hat
i s i mpl ement ed b y Panc ak eHouseMenu and Di ner Menu. Eac h menu
c l ass assumes t he r esponsi b i l i t y of c r eat i ng a c onc r et e It er at or
t hat i s appr opr i at e f or i t s i nt er nal i mpl ement at i on of t he menu
i t ems.
It a ls o p la ce s th e ta s k o f tra v e rs a l o n th e ite ra to r
o b je ct, no t o n th e a g g re g a te , w h ich s im p lifie s th e
a g g re g a te inte rfa ce a nd im p le m e nta tio n, a nd p la ce s
th e re s p o ns ib ility w h e re it s h o uld b e .
B R AIN PO W ER
T he class diagram for the Iterator Pattern looks very similar to another
pattern you’ve studied; can you think of what it is? Hint: a subclass
decides which object to create.
B R AIN PO W ER
Examine these classes and determine which ones have multiple
responsibilities.
B R AIN PO W ER
Determine if these classes have low or high cohesion.
A: Those ar e t he “c l assi c ” met hod names t hat hav e b een used. These
names hav e c hanged ov er t i me and w e now hav e nex t (), hasN ex t (),
and ev en r emov e() i n jav a.ut i l .It er at or .
Let ’s l ook at t he c l assi c met hods. The nex t () and c ur r ent It em() hav e
b een mer ged i nt o one met hod i n jav a.ut i l . The i sDone() met hod has
b ec ome hasN ex t (), b ut w e hav e no met hod c or r espondi ng t o f i r st ().
That ’s b ec ause i n Jav a w e t end t o just get a new i t er at or w henev er
w e need t o st ar t t he t r av er sal ov er . N ev er t hel ess, y ou c an see t her e
i s v er y l i t t l e di f f er enc e i n t hese i nt er f ac es. In f ac t , t her e i s a
w hol e r ange of b ehav i or s y ou c an gi v e y our i t er at or s. The r emov e()
met hod i s an ex ampl e of an ex t ensi on i n jav a.ut i l .It er at or .
A: Pr ob ab l y . If y ou hav e a c ommon It er at or i nt er f ac e, i t w i l l
c er t ai nl y mak e i t easi er f or y ou t o mi x and mat c h y our ow n
aggr egat es w i t h Jav a aggr egat es l i k e A r r ay Li st and V ec t or . But
r ememb er , i f y ou need t o add f unc t i onal i t y t o y our It er at or
i nt er f ac e f or y our aggr egat es, y ou c an al w ay s ex t end t he It er at or
i nt er f ac e.
W e c an i t er at e ov er A r r ay Li st t he w ay w e hav e b een:
SER IO U S C O D IN G
You probably noticed the forEach() method in the Iterable menu. It’s used
as the basis for Java’s enhanced for loop, but you can also use it directly
with Iterables. Here’s how it works:
1.
____________________________________________________________
____
2.
____________________________________________________________
____
3.
____________________________________________________________
____
C O D E U P C L O SE
HashMap is a little more complex than ArrayList because it supports both
keys and values, but we can still get an Iterator for the values (which are
the MenuItems).
B R AIN PO W ER
Are we violating the Principle of Least Knowledge here? What can we do
about it?
W AT C H IT !
HashMap is one of a few classes that indirectly supports Iterator.
Code Magnets
The Chef s hav e dec i ded t hat t hey w ant t o b e ab l e t o al t er nat e t hei r
l unc h menu i t ems; i n ot her w or ds, t hey w i l l of f er some i t ems on
Monday , W ednesday , Fr i day , and Sunday , and ot her i t ems on
Tuesday , Thur sday , and Sat ur day . Someone al r eady w r ot e t he c ode
f or a new “A l t er nat i ng” Di ner Menu It er at or so t hat i t al t er nat es
t he menu i t ems, b ut she sc r amb l ed i t up and put i t on t he f r i dge i n
t he Di ner as a jok e. Can y ou put i t b ac k t oget her ? Some of t he c ur l y
b r ac es f el l on t he f l oor and t hey w er e t oo smal l t o pi c k up, so f eel
f r ee t o add as many of t hose as y ou need.
Is the Waitress ready for prime time?
The W ai t r ess has c ome a l ong w ay , b ut y ou’v e got t a admi t t hose
t hr ee c al l s t o pr i nt Menu() ar e l ook i ng k i nd of ugl y .
B R AIN PO W ER
T he Waitress still needs to make three calls to printMenu(), one for each
menu. Can you think of a way to combine the menus so that only one call
needs to be made? Or perhaps so that one Iterator is passed to the
Waitress to iterate over all the menus?
Sounds l i k e t he c hef i s on t o somet hi ng. Let ’s gi v e i t a t r y :
What do we need?
The t i me has c ome t o mak e an ex ec ut i v e dec i si on t o r ew or k t he
c hef ’s i mpl ement at i on i nt o somet hi ng t hat i s gener al enough t o
w or k ov er al l t he menus (and now sub menus). That ’s r i ght , w e’r e
goi ng t o t el l t he c hef s t hat t he t i me has c ome f or us t o r ei mpl ement
t hei r menus.
B R AIN PO W ER
How would you handle this new wrinkle to our design requirements? T hink
about it before turning the page.
N O TE
All components must implement the MenuComponent
interface; however, because leaves and nodes have
different roles we can’t always define a default
implementation for each method that makes sense.
Sometimes the best you can do is throw a runtime
exception.
N O TE
NOTE: this output is based on the complete source.
There is some truth to that observ ation. W e c oul d say t hat t he
Composi t e Pat t er n t ak es t he Si ngl e Responsi b i l i t y Pr i nc i pl e and
t r ades i t f or trans parenc y . W hat ’s t r anspar enc y ? W el l , b y al l ow i ng
t he Component i nt er f ac e t o c ont ai n t he c hi l d management
oper at i ons and t he l eaf oper at i ons, a c l i ent c an t r eat b ot h
c omposi t es and l eav es uni f or ml y ; so w het her an el ement i s a
c omposi t e or l eaf node b ec omes t r anspar ent t o t he c l i ent .
HeadFirst: We’re here tonight speaking with the Composite Pattern. Why
don’t you tell us a little about yourself, Composite?
Composite: Imagine a graphical user interface (GUI); there you’ll often find
a top-level component like a Frame or a Panel, containing other
components, like menus, text panes, scrollbars, and buttons. So your GUI
consists of several parts, but when you display it, you generally think of it
as a whole. You tell the top-level component to display, and count on that
component to display all its parts. We call the components that contain
other components, composite objects, and components that don’t contain
other components leaf objects.
HeadFirst: Is that what you mean by treating the objects uniformly? Having
common methods you can call on composites and leaves?
HeadFirst: T hat implies that every object has the same interface. What if
you have objects in your composite that do different things?
Composite: Well, there are a couple of ways to handle it; sometimes you
can just do nothing, or return null or false—whatever makes sense in your
application. Other times you’ll want to be more proactive and throw an
exception. Of course, then the client has to be willing to do a little work and
make sure that the method call didn’t do something unexpected.
HeadFirst: But if the client doesn’t know which kind of object they’re
dealing with, how would they ever know which calls to make without
checking the type?
Composite: If you’re a little creative you can structure your methods so that
the default implementations do something that does make sense. For
instance, if the client is calling getChild() on the composite, this makes
sense. And it makes sense on a leaf too, if you think of the leaf as an
object with no children.
HeadFirst: Ah...smart. But I’ve heard some clients are so worried about
this issue that they require separate interfaces for different objects so they
aren’t allowed to make nonsensical method calls. Is that still the
Composite Pattern?
Composite: Yes. It’s a much safer version of the Composite Pattern, but it
requires the client to check the type of every object before making a call so
the object can be cast correctly.
HeadFirst: Tell us a little more about how these composite and leaf
objects are structured.
Composite: Actually, there are. One is the ordering of children. What if you
have a composite that needs to keep its children in a particular order?
T hen you’ll need a more sophisticated management scheme for adding
and removing children, and you’ll have to be careful about how you traverse
the hierarchy.
HeadFirst: Caching?
HeadFirst: Well, there’s a lot more to the Composite Patterns than I ever
would have guessed. Before we wrap this up, one more question: what do
you consider your greatest strength?
Composite: I think I’d definitely have to say simplifying life for my clients.
My clients don’t have to worry about whether they’re dealing with a
composite object or a leaf object, so they don’t have to write if statements
everywhere to make sure they’re calling the right methods on the right
objects. Often, they can make one method call and execute an operation
over an entire structure.
1 3. W e enc apsul at ed t hi s.
DOWN
2. Has no c hi l dr en.
1 0. A c omponent c an b e a c omposi t e or t hi s.
W H O D O ES W H AT ?
Match each pattern with its description:
Patte
rn Description
SH AR PEN YO U R PEN C IL
SO L U T IO N
Based on our implementation of printMenu(), which of the following apply?
3. add createIterator() and return an Iterator that can step through the
HashMap values
W H O D O ES W H AT ?
Match each pattern with its description:
Java Breakers
N O TE
At least that’s their story—we think they just got bored with the
circa 1800s technology and needed to find a way to make their
jobs more exciting.
Cubicle Conversation
Judy : Thi s di agr am l ook s l i k e a st at e di agr am.
F rank: Yes...
Design Puzzle
Dr aw a st at e di agr am f or a Gumb al l Mac hi ne t hat handl es t he 1 i n
1 0 c ont est . In t hi s c ont est , 1 0% of t he t i me t he Sol d st at e l eads t o t w o
b al l s b ei ng r el eased, not one. Chec k y our answ er w i t h our s (at t he
end of t he c hapt er ) t o mak e sur e w e agr ee b ef or e y ou go f ur t her ...
The messy STATE of things...
Just b ec ause y ou’v e w r i t t en y our gumb al l mac hi ne usi ng a w el l -
t hought -out met hodol ogy doesn’t mean i t ’s goi ng t o b e easy t o
ex t end. In f ac t , w hen y ou go b ac k and l ook at y our c ode and t hi nk
ab out w hat y ou’l l hav e t o do t o modi f y i t , w el l ...
SH AR PEN YO U R PEN C IL
Which of the following describe the state of our implementation? (Choose
all that apply.)
Judy : Ex ac t l y .
Let ’s st ar t w i t h t he N oQuar t er St at e:
B R AIN PO W ER
Look back at the GumballMachine implementation. If the crank is turned
and not successful (say the customer didn’t insert a quarter first), we call
dispense() anyway, even though it’s unnecessary. How might you fix this?
SH AR PEN YO U R PEN C IL
We have one remaining class we haven’t implemented: SoldOutState. Why
don’t you implement it? To do this, carefully think through how the Gumball
Machine should behave in each situation. Check your answer before
moving on...
}
}
T race the steps of the Gumball Machine starting with the NoQuarter state.
Also annotate the diagram with actions and output of the machine. For this
exercise you can assume there are plenty of gumballs in the machine.
N O TE
The State Pattern allows an object to alter its behavior when
its internal state changes. The object will appear to change its
class.
W hat ab out t he sec ond par t of t he def i ni t i on? W hat does i t mean f or
an ob jec t t o “appear t o c hange i t s c l ass”? Thi nk ab out i t f r om t he
per spec t i v e of a c l i ent : i f an ob jec t y ou’r e usi ng c an c ompl et el y
c hange i t s b ehav i or , t hen i t appear s t o y ou t hat t he ob jec t i s
ac t ual l y i nst ant i at ed f r om anot her c l ass. In r eal i t y , how ev er , y ou
k now t hat w e ar e usi ng c omposi t i on t o gi v e t he appear anc e of a
c l ass c hange b y si mpl y r ef er enc i ng di f f er ent st at e ob jec t s.
Sanity check...
N O TE
Dammit Jim, I’m a gumball machine, not a
computer!
We almost forgot!
SH AR PEN YO U R PEN C IL
We need you to write the refill() method for the Gumball machine. It has
one argument—the number of gumballs you’re adding to the machine—and
should update the gumball machine count and reset the machine’s state.
W H O D O ES W H AT ?
Match each pattern with its description:
Pattern Description
SH AR PEN YO U R PEN C IL
SO L U T IO N
Which of the following describe the state of our implementation? (Choose
all that apply.) Here’s our solution.
N OT E
In the Sold Out state, we really can’t do anything until someone refills
the Gumball Machine.
SH AR PEN YO U R PEN C IL
SO L U T IO N
To implement the states, we first need to define what the behavior will be
when the corresponding action is called. Annotate the diagram below with
the behavior of each action in each class; here’s our solution.
W H O D O ES W H AT SO L U T IO N ?
Match each pattern with its description:
SH AR PEN YO U R PEN C IL
SO L U T IO N
To refill the Gumball Machine, we add a refill() method to the State
interface, which each State must implement. In every state except
SoldOutState, the method does nothing. In SoldOutState, refill() transitions
to NoQuarterState. We also add a refill() method to GumballMachine that
adds to the count of gumballs, and then calls the current state’s refill()
method.
Chapter 11. Controlling Object
Access: The Proxy Pattern
B R AIN PO W ER
Should making remote calls be totally transparent? Is that a good idea?
What might be a problem with that approach?
You mi ght w ant t o mak e sur e y our seat b el t i s f ast ened; t her e ar e a
l ot of st eps—b ut not hi ng t o b e t oo w or r i ed ab out .
Step one:
Step two:
Step three:
Step four:
1 . Extend j av a.rmi.Remote
N O TE
Check out your favorite Java reference if you need
to refresh your memory on Serializable.
Your new super c l ass, U ni c ast Remot eOb jec t , has one l i t t l e
pr ob l em—i t s c onst r uc t or t hr ow s Remot eEx c ept i on. The
onl y w ay t o deal w i t h t hi s i s t o dec l ar e a c onst r uc t or f or
y our r emot e i mpl ement at i on, just so t hat y ou hav e a
pl ac e t o dec l ar e Remot eEx c ept i on. Rememb er , w hen a
c l ass i s i nst ant i at ed, i t s super c l ass c onst r uc t or i s al w ay s
c al l ed. If y our super c l ass c onst r uc t or t hr ow s an
ex c ept i on, y ou hav e no c hoi c e b ut t o dec l ar e t hat y our
c onst r uc t or al so t hr ow s an ex c ept i on.
C O D E U P C L O SE
How it works...
Naming.lookup("rmi://127.0.0.1/RemoteHello");
B R AIN PO W ER
Stop and think through how we’re going to adapt the gumball machine
code to work with a remote proxy. Feel free to make some notes here about
what needs to change and what’s going to be different than the previous
version.
W e’l l st ar t w i t h t he r emot e i nt er f ac e:
W e hav e one r et ur n t y pe t hat i sn’t Ser i al i zab l e: t he St at e c l ass.
Let ’s f i x i t up...
C O D E U P C L O SE
And now let’s put the monitor in the hands of the CEO.
Hopefully, this time he’ll love it:
By inv o k ing m e th o d s o n th e p ro xy , w e m a k e a re m o te
ca ll a cro s s th e w ire , a nd g e t b a ck a S tring , a n inte g e r,
a nd a S ta te o b je ct. Be ca us e w e a re us ing a p ro xy , th e
Gum b a ll Mo nito r d o e s n’t k no w , o r ca re , th a t ca lls a re
re m o te (o th e r th a n h a v ing to w o rry a b o ut re m o te
e xce p tio ns ).
2. get St at e() i s c al l ed on t he pr ox y , w hi c h f or w ar ds t he c al l
t o t he r emot e ser v i c e. The sk el et on r ec ei v es t he r equest
and t hen f or w ar ds i t t o t he Gumb al l Mac hi ne.
N O TE
The Proxy Pattern provides a surrogate or placeholder for
another object to control access to it.
Remote Proxy
W i t h t he Remot e Pr ox y , t he pr ox y ac t s as a l oc al r epr esent at i v e
f or an ob jec t t hat l i v es i n a di f f er ent JV M. A met hod c al l on t he
pr ox y r esul t s i n t he c al l b ei ng t r ansf er r ed ov er t he w i r e and
i nv ok ed r emot el y , and t he r esul t b ei ng r et ur ned b ac k t o t he pr ox y
and t hen t o t he Cl i ent .
Virtual Proxy
The V i r t ual Pr ox y ac t s as a r epr esent at i v e f or an ob jec t t hat may
b e ex pensi v e t o c r eat e. The V i r t ual Pr ox y of t en def er s t he c r eat i on
of t he ob jec t unt i l i t i s needed; t he V i r t ual Pr ox y al so ac t s as a
sur r ogat e f or t he ob jec t b ef or e and w hi l e i t i s b ei ng c r eat ed. A f t er
t hat , t he pr ox y del egat es r equest s di r ec t l y t o t he Real Sub jec t .
C O D E U P C L O SE
C O D E W AY U P C L O SE
D ESIG N PU Z Z L E
T he ImageProxy class appears to have two states that are controlled by
conditional statements. Can you think of another pattern that might clean
up this code? How would you redesign ImageProxy?
N ow l et ’s r un t he t est dr i v e:
Things to try...
Q: How do I make clients use the Proxy rather than the Real
Subj ect?
A: Good quest i on. One c ommon t ec hni que i s t o pr ov i de a f ac t or y
t hat i nst ant i at es and r et ur ns t he sub jec t . Bec ause t hi s happens i n a
f ac t or y met hod, w e c an t hen w r ap t he sub jec t w i t h a pr ox y b ef or e
r et ur ni ng i t . The c l i ent nev er k now s or c ar es t hat i t ’s usi ng a
pr ox y i nst ead of t he r eal t hi ng.
In our dat i ng ser v i c e w e w ant t o mak e sur e t hat a c ust omer c an set
hi s ow n i nf or mat i on w hi l e pr ev ent i ng ot her s f r om al t er i ng i t . W e
al so w ant t o al l ow just t he opposi t e w i t h t he Geek r at i ngs: w e w ant
t he ot her c ust omer s t o b e ab l e t o set t he r at i ng, b ut not t hat
par t i c ul ar c ust omer . W e al so hav e a numb er of get t er met hods i n
Per son, and b ec ause none of t hese r et ur n pr i v at e i nf or mat i on, any
c ust omer shoul d b e ab l e t o c al l t hem.
Step one:
Cr eat e t w o I nv ocationHandlers.
Step two:
Step three:
Ther e’s onl y one met hod, i nv ok e(), and no mat t er w hat met hods get
c al l ed on t he pr ox y , t he i nv ok e() met hod i s w hat get s c al l ed on t he
handl er . Let ’s see how t hi s w or k s:
EXER C ISE
T he NonOwnerInvocationHandler works just like the
OwnerInvocationHandler except that it allow s calls to setGeekRating() and
it disallow s calls to any other set method. Go ahead and write this handler
yourself:
Take it further: can you write a method called getProxy() that takes a handler
and a person and returns a proxy that uses that handler?
W H O D O ES W H AT ?
Match each pattern with its description:
Pattern Description
Facade Wraps another object and provides additional behavior for it.
Our job i sn’t done; w e’r e sur e y ou’r e goi ng t o see mor e v ar i at i ons of
t hi s pat t er n i n t he r eal w or l d, so gi v e us a hand i n c at al ogi ng mor e
pr ox i es. Let ’s t ak e a l ook at t he ex i st i ng c ol l ec t i on:
Design Patterns Crossword
It ’s b een a LON G c hapt er . W hy not unw i nd b y doi ng a c r ossw or d
puzzl e b ef or e i t ends?
ACROSS
1 6. The A l b um v i ew er used t hi s k i nd of pr ox y .
1 7 . In RMI, t he pr ox y i s c al l ed t hi s.
DOWN
Java’s built-in support for Proxy can build a dynamic proxy class
on demand and dispatch all calls on it to a handler of your
choosing.
EXER C ISE SO L U T IO N
T he NonOwnerInvocationHandler works just like the
OwnerInvocationHandler except that it allow s calls to setGeekRating() and
it disallow s calls to any other set method.
import java.lang.reflect.*;
try {
if (method.getName().startsWith("get")) {
return method.invoke(person, args);
} else if
(method.getName().equals("setGeekRating")) {
return method.invoke(person, args);
} else if
(method.getName().startsWith("set")) {
throw new IllegalAccessException();
}
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
D ESIG N PU Z Z L E SO L U T IO N
T he ImageProxy class appears to have two states that are controlled by
conditional statements. Can you think of another pattern that might clean
up this code? How would you redesign ImageProxy?
SH AR PEN YO U R PEN C IL
SO L U T IO N
While it is a little complicated, there isn’t much to creating a dynamic
proxy. Why don’t you write getNonOwnerProxy(), which returns a proxy for the
NonOwnerInvocationHandler? Here’s our solution:
W H O D O ES W H AT SO L U T IO N ?
Match each pattern with its description:
package headfirst.designpatterns.proxy.virtualproxy;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class ImageProxyTestDrive {
ImageComponent imageComponent;
JFrame frame = new JFrame("Album Cover Viewer");
JMenuBar menuBar;
JMenu menu;
Hashtable<String, String> albums = new Hashtable<String, String>
();
public static void main (String[] args) throws Exception {
ImageProxyTestDrive testDrive = new ImageProxyTestDrive();
}
albums.put("Ima","http://images.amazon.com/images/P/B000005IRM.01.LZ
ZZZZZZ.jpg");
albums.put("Karma","http://images.amazon.com/images/P/B000005DCB.01.
LZZZZZZZ.gif");
albums.put("MCMXC
a.D.","http://images.amazon.com/images/P/B000002URV.01.LZZZZZZZ.jpg"
);
albums.put("Northern
Exposure","http://images.amazon.com/images/P/B000003SFN.01.LZZZZZZZ.
jpg");
albums.put("Selected Ambient Works, Vol.
2","http://images.amazon.com/images/P/B000002MNZ.01.LZZZZZZZ.jpg");
}
URL getAlbumUrl(String name) {
try {
return new URL((String)albums.get(name));
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
}
}
package headfirst.designpatterns.proxy.virtualproxy;
import java.net.*;
import java.awt.*;
import javax.swing.*;
package headfirst.designpatterns.proxy.virtualproxy;
import java.awt.*;
import javax.swing.*;
Working together
One of t he b est w ay s t o use pat t er ns i s t o get t hem out of t he house
so t hey c an i nt er ac t w i t h ot her pat t er ns. The mor e y ou use pat t er ns
t he mor e y ou’r e goi ng t o see t hem show i ng up t oget her i n y our
desi gns. W e hav e a spec i al name f or a set of pat t er ns t hat w or k
t oget her i n a desi gn t hat c an b e appl i ed ov er many pr ob l ems: a
c om pound pattern. That ’s r i ght , w e ar e now t al k i ng ab out pat t er ns
made of pat t er ns!
Duck reunion
A s y ou’v e al r eady hear d, w e’r e goi ng t o get t o w or k w i t h t he duc k s
agai n. Thi s t i me t he duc k s ar e goi ng t o show y ou how pat t er ns c an
c oex i st and ev en c ooper at e w i t hi n t he same sol ut i on.
B R AIN PO W ER
Let’s say we wanted to be able to use a Goose anywhere
we’d want to use a Duck. After all, geese make noise; geese
fly; geese swim. Why can’t we have Geese in the simulator?
Q U AC K O L O G Y
Quackologists are fascinated by all aspects of Quackable
behavior. One thing Quackologists have always wanted to
study is the total number of quacks made by a flock of ducks.
SH AR PEN YO U R PEN C IL
We’re still directly instantiating Geese by relying on concrete
classes. Can you write an Abstract Factory for Geese? How
should it handle creating “goose ducks”?
C O D E U P C L O SE
Did you notice that we tried to sneak a Design Pattern by you
without mentioning it?
SH AR PEN YO U R PEN C IL
We haven’t changed the implementation of one Quackable,
the QuackCounter decorator. We need to make it an
Observable too. Why don’t you write that one:
Meet Model-View-Controller
Imagi ne y ou’r e usi ng y our f av or i t e musi c pl ay er , l i k e i Tunes. You
c an use i t s i nt er f ac e t o add new songs, manage pl ay l i st s, and r ename
t r ac k s. The pl ay er t ak es c ar e of mai nt ai ni ng a l i t t l e dat ab ase of al l
y our songs al ong w i t h t hei r assoc i at ed names and dat a. It al so t ak es
c ar e of pl ay i ng t he songs and, as i t does, t he user i nt er f ac e i s
c onst ant l y updat ed w i t h t he c ur r ent song t i t l e, t he r unni ng t i me,
and so on.
W hen t he c ont r ol l er r ec ei v es an ac t i on f r om t he v i ew , i t
may need t o t el l t he v i ew t o c hange as a r esul t . For
ex ampl e, t he c ont r ol l er c oul d enab l e or di sab l e c er t ai n
b ut t ons or menu i t ems i n t he i nt er f ac e.
Observer
Strategy
Composite
R EAD Y B AK E C O D E
T his model uses an audio clip to generate beats. You can check out the
complete implementation of all the DJ classes in the Java source files,
available on the wickedlysmart.com site, or look at the code at the end of
the chapter.
The View
N ow t he f un st ar t s; w e get t o hook up a v i ew and v i sual i ze t he
Beat Model !
B R AIN PO W ER
Our BeatModel makes no assumptions about the view. T he model is
implemented using the Observer Pattern, so it just notifies any view
registered as an observer when its state changes. T he view uses the
model’s API to get access to the state. We’ve implemented one type of
view; can you think of other views that could make use of the notifications
and state in the BeatModel?
A textual view that displays a music genre based on the BPM (ambient,
downbeat, techno, etc.).
____________________________________________________________
____
____________________________________________________________
____
W AT C H IT !
The code on these two pages is j ust an outline!
What w e’ve done here is split ONE class into TWO, show ing you one part
of the view on this page, and the other part on the next page. All this code
is really in ONE class—DJView .java. It’s all listed at the end of the
chapter.
D ESIG N PU Z Z L E
You’ve seen that the view and controller together make use of the Strategy
Pattern. Can you draw a class diagram of the two that represents this
pattern?
N O TE
Make sure you have the file clip.wav at the top level of the code
folder!
Things to try
3. Notice how the beat bar alway s keeps up with the beat
since it’s an observ er of the model.
4. Put on y our fav orite song and see if y ou can match the
beat by using the increase and decrease controls.
Exploring Strategy
Let ’s t ak e t he St r at egy Pat t er n just a l i t t l e f ur t her t o get a b et t er
f eel f or how i t i s used i n MV C. W e’r e goi ng t o see anot her f r i endl y
pat t er n pop up t oo—a pat t er n y ou’l l of t en see hangi ng ar ound t he
MV C t r i o: t he A dapt er Pat t er n.
Thi nk f or a sec ond ab out w hat t he DJ V i ew does: i t di spl ay s a b eat
r at e and a pul se. Does t hat sound l i k e somet hi ng el se? How ab out a
hear t b eat ? It just so happens t hat w e hav e a hear t moni t or c l ass;
her e’s t he c l ass di agr am:
B R AIN PO W ER
It certainly would be nice to reuse our current view with the HeartModel, but
we need a controller that works with this model. Also, the interface of the
HeartModel doesn’t match what the view expects because it has a
getHeartRate() method rather than a getBPM(). How would you design a set
of classes to allow the view to be reused with the new model? Jot down
your class design ideas below.
And that’s it! Now it’s time for some test code...
Q: Y ou’v e talked a lot about the state of the model. Does this
mean it has the State Pattern in it?
Q: Does the v iew alway s hav e to ask the model for its state?
Couldn’t we use the push model and send the model’s state with
the update notification?
Y es!
Exercise Solutions
SH AR PEN YO U R PEN C IL
SO L U T IO N
T he QuackCounter is a Quackable too. When we change Quackable to
extend QuackObservable, we have to change every class that implements
Quackable, including QuackCounter:
SH AR PEN YO U R PEN C IL
SO L U T IO N
What if our Quackologist wants to observe an entire flock? What does that
mean anyway? T hink about it like this: if we observe a composite, then
we’re observing everything in the composite. So, when you register with a
flock, the flock composite makes sure you get registered with all its
children, which may include other flocks.
SH AR PEN YO U R PEN C IL
SO L U T IO N
We’re still directly instantiating Geese by relying on concrete classes. Can
you write an Abstract Factory for Geese? How should it handle creating
“goose ducks”?
D ESIG N PU Z Z L E SO L U T IO N
You’ve seen that the view and controller together make use of the Strategy
Pattern. Can you draw a class diagram of the two that represents this
pattern?
package headfirst.designpatterns.combined.djview;
package headfirst.designpatterns.combined.djview;
void on();
void off();
package headfirst.designpatterns.combined.djview;
import java.util.*;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.io.*;
import javax.sound.sampled.Line;
clip.open(AudioSystem.getAudioInputStream(resource));
}
catch(Exception ex) {
System.out.println("Error: Can’t load clip");
System.out.println(ex);
}
}
The View
package headfirst.designpatterns.combined.djview;
package headfirst.designpatterns.combined.djview;
package headfirst.designpatterns.combined.djview;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
bpmLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
bpmOutputLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
controlFrame.getRootPane().setDefaultButton(setBPMButton);
controlFrame.getContentPane().add(controlPanel,
BorderLayout.CENTER);
controlFrame.pack();
controlFrame.setVisible(true);
}
The Controller
package headfirst.designpatterns.combined.djview;
package headfirst.designpatterns.combined.djview;
package headfirst.designpatterns.combined.djview;
package headfirst.designpatterns.combined.djview;
import java.util.*;
public HeartModel() {
thread = new Thread(this);
thread.start();
}
for(;;) {
int change = random.nextInt(10);
if (random.nextInt(2) == 0) {
change = 0 - change;
}
int rate = 60000/(time + change);
if (rate < 120 && rate > 50) {
time += change;
notifyBeatObservers();
if (rate != lastrate) {
lastrate = rate;
notifyBPMObservers();
}
}
try {
Thread.sleep(time);
} catch (Exception e) {}
}
}
public int getHeartRate() {
return 60000/time;
}
package headfirst.designpatterns.combined.djview;
The Controller
package headfirst.designpatterns.combined.djview;
Ahhhh, now y ou’re ready for a bright new world filled with
Design Patterns. But , b ef or e y ou go openi ng al l t hose new door s of
oppor t uni t y , w e need t o c ov er a f ew det ai l s t hat y ou’l l enc ount er
out i n t he r eal w or l d—t hat ’s r i ght , t hi ngs get a l i t t l e mor e c ompl ex
t han t hey ar e her e i n Ob jec t v i l l e. Come al ong, w e’v e got a ni c e
gui de t o hel p y ou t hr ough t he t r ansi t i on on t he nex t page...
N O TE
A Pattern is a solution to a problem in a context.
N O TE
Example: You have a collection of objects.
N O TE
You need to step through the objects without exposing the
collection’s implementation.
N O TE
Encapsulate the iteration into a separate class.
Context: I’v e l oc k ed my k ey s i n t he c ar .
B R AIN PO W ER
We followed the Design Pattern definition and defined a problem, a
context, and a solution (which works! ). Is this a pattern? If not, how did it
fail? Could we fail the same way when defining an OO Design Pattern?
T H ER E AR E N O D U M B Q U EST IO N S
Q: Am I going to see pattern descriptions that are stated as a problem, a
context, and a solution?
A: Of course you can alter it. Like design principles, patterns are not meant
to be laws or rules; they are guidelines that you can alter to fit your needs.
As you’ve seen, a lot of real-world examples don’t fit the classic pattern
designs.
However, when you adapt patterns, it never hurts to document how your
pattern differs from the classic design—that way, other developers can
quickly recognize the patterns you’re using and any differences between
your pattern and the classic pattern.
G EEK B IT S: M AY T H E F O R C E
B E W IT H YO U
T he Design Pattern definition tells us that the problem consists of a goal
and a set of constraints. Pattern gurus have a term for these: they call them
forces. Why? Well, we’re sure they have their own reasons, but if you
remember the movie, the force “shapes and controls the Universe.”
Likewise, the forces in the pattern definition shape and control the
solution. Only when a solution balances both sides of the force (the light
side: your goal, and the dark side: the constraints) do we have a useful
pattern.
T his “force” terminology can be quite confusing when you first see it in
pattern discussions, but just remember that there are two sides of the force
(goals and constraints) and that they need to be balanced or resolved to
create a pattern solution. Don’t let the lingo get in your way and may the
force be with you!
F rank: Fi l l us i n, Ji m. I’v e just b een l ear ni ng pat t er ns b y r eadi ng a
f ew ar t i c l es her e and t her e.
F rank: W hi c h c at al og ar e y ou l ook i ng at ?
F rank: GoF?
Jim: Hol d on, Fr ank ; ac t ual l y , t he name i s r eal l y i mpor t ant . W hen
w e hav e a name f or a pat t er n, i t gi v es us a w ay t o t al k ab out t he
pat t er n; y ou k now , t hat w hol e shar ed v oc ab ul ar y t hi ng.
Jim: Ther e ar e sev er al sec t i ons t hat desc r i b e t he c l ass desi gn al ong
w i t h al l t he c l asses t hat mak e i t up and w hat t hei r r ol es ar e. Ther e
i s al so a sec t i on t hat desc r i b es how t o i mpl ement t he pat t er n and
of t en sampl e c ode t o show y ou how .
Jim: Ex ac t l y !
Hav e others try y our patterns; then refine and refine some
more. Don’t ex pec t t o get y our pat t er n r i ght t he f i r st t i me. Thi nk
of y our pat t er n as a w or k i n pr ogr ess t hat w i l l i mpr ov e ov er t i me.
Hav e ot her dev el oper s r ev i ew y our c andi dat e pat t er n, t r y i t out ,
and gi v e y ou f eedb ac k . Inc or por at e t hat f eedb ac k i nt o y our
desc r i pt i on and t r y agai n. Your desc r i pt i on w i l l nev er b e per f ec t ,
b ut at some poi nt i t shoul d b e sol i d enough t hat ot her dev el oper s
c an r ead and under st and i t .
Don’t forget the Rule of Three. Rememb er , unl ess y our pat t er n
has b een suc c essf ul l y appl i ed i n t hr ee r eal -w or l d sol ut i ons, i t c an’t
qual i f y as a pat t er n. That ’s anot her good r eason t o get y our pat t er n
i nt o t he hands of ot her s so t hey c an t r y i t , gi v e f eedb ac k , and al l ow
y ou t o c onv er ge on a w or k i ng pat t er n.
W H O D O ES W H AT ?
Match each pattern with its description:
Pattern Categories
Her e’s t he gr oupi ng of pat t er ns i nt o c at egor i es. You pr ob ab l y
f ound t he ex er c i se di f f i c ul t , b ec ause many of t he pat t er ns seem
l i k e t hey c oul d f i t i nt o mor e t han one c at egor y . Don’t w or r y ,
ev er y one has t r oub l e f i gur i ng out t he r i ght c at egor i es f or t he
pat t er ns.
T H ER E AR E N O D U M B Q U EST IO N S
Q: Are these the only classification schemes?
A: No, other schemes have been proposed. Some other schemes start
with the three categories and then add subcategories, like “Decoupling
Patterns.” You’ll want to be familiar with the most common schemes for
organizing patterns, but also feel free to create your own, if it helps you to
understand the patterns better.
A: It certainly gives you a framework for the sake of comparison. But many
people are confused by the creational, structural, and behavioral
categories; often a pattern seems to fit into more than one category. T he
most important thing is to know the patterns and the relationships among
them. When categories help, use them!
A: Yes, lots of developers say that! Here’s the thinking behind the Gang of
Four classification: structural patterns describe how classes and objects
are composed to create new structures or new functionality. T he Decorator
Pattern allows you to compose objects by wrapping one object with
another to provide new functionality. So the focus is on how you compose
the objects dynamically to gain functionality, rather than on the
communication and interconnection between objects, which is the
purpose of behavioral patterns. But remember, the intent of these patterns
is different, and that’s often the key to understanding which category a
pattern belongs to.
Guru a nd S tud e nt...
S tud e nt: Yes , I ’v e jus t learned about pattern c las s ific ation and I ’m
c onfus ed.
Guru: Continue...
Know ing w hen a pat t er n appl i es i s w her e y our ex per i enc e and
k now l edge c ome i n. Onc e y ou’r e sur e a si mpl e sol ut i on w i l l not
meet y our needs, y ou shoul d c onsi der t he pr ob l em al ong w i t h t he
set of c onst r ai nt s under w hi c h t he sol ut i on w i l l need t o oper at e—
t hese w i l l hel p y ou mat c h y our pr ob l em t o a pat t er n. If y ou’v e got a
good k now l edge of pat t er ns, y ou may k now of a pat t er n t hat i s a
good mat c h. Ot her w i se, sur v ey pat t er ns t hat l ook l i k e t hey mi ght
sol v e t he pr ob l em. The i nt ent and appl i c ab i l i t y sec t i ons of t he
pat t er ns c at al ogs ar e par t i c ul ar l y usef ul f or t hi s. Onc e y ou’v e
f ound a pat t er n t hat appear s t o b e a good mat c h, mak e sur e i t has a
set of c onsequenc es y ou c an l i v e w i t h and st udy i t s ef f ec t on t he
r est of y our desi gn. If ev er y t hi ng l ook s good, go f or i t !
Take out what you don’t really need. Don’t be afraid to remove a
Design Pattern from your design.
Guru: Student, your initial training is almost complete. What are your
plans?
Student: I’m going to Disneyland! And then I’m going to start creating lots
of code w ith patterns!
Guru: Whoa, hold on. Never use your big guns unless you have to.
Student: What do you mean, Guru? Now that I’ve learned design patterns,
shouldn’t I be using them in all my designs to achieve maximum pow er,
flexibility, and manageability?
Guru: No; patterns are a tool, and a tool that should only be used w hen
needed. You’ve also spent a lot of time learning design principles. Alw ays
start from your principles and create the simplest code you can that does
the job. How ever, if you see the need for a pattern emerge, then use it.
Guru: That should not be your goal w hen beginning a design. Let patterns
emerge naturally as your design progresses.
Guru: Introduce a pattern w hen you are sure it’s necessary to solve a
problem in your design, or w hen you are quite sure that it is needed to deal
w ith a future change in the requirements of your application.
Guru: Yes; learning to manage the complexity and change in softw are is a
lifelong pursuit. But now that you know a good set of patterns, the time
has come to apply them w here needed in your design and to continue
learning more patterns.
WARNING
Overuse of design patterns can lead to code that is downright
overengineered. Always go with the simplest solution that does
the job and introduce patterns where the need emerges.
How di d t hey get t hat name? N o one k now s f or sur e; i t ’s just a name
t hat st uc k . But t hi nk ab out i t : i f y ou’r e goi ng t o hav e a “gang
el ement ” r unni ng ar ound Ob jec t v i l l e, c oul d y ou t hi nk of a ni c er
b unc h of guy s? In f ac t , t hey ’v e ev en agr eed t o pay us a v i si t ...
Websites
or ei l l y .c om
Other Resources
N O TE
An Anti-Pattern tells you how to go from a problem to a BAD
solution.
Always use the simplest solution that meets your needs, even if
it doesn’t include a pattern.
Like any community, the patterns community has its own lingo.
Don’t let that hold you back. Having read this book, you now
know most of it.
Leaving Objectville...
Bridge
Use the Bridge Pattern to v ary not only y our implementations,
but also y our abstractions.
A scenario
Your dilemma
B R ID G E B EN EF IT S
B R ID G E U SES AN D D R AW B AC K S
Increases complexity.
Builder
Use the Builder Pattern to encapsulate the construction of a
product and allow it to be constructed in steps.
A scenario
B U IL D ER U SES AN D D R AW B AC K S
Chain of Responsibility
Use the Chain of Responsibility Pattern when y ou want to giv e
more than one obj ect a chance to handle a request.
A scenario
Mi ght y Gumb al l has b een get t i ng mor e emai l t han t hey c an handl e
si nc e t he r el ease of t he Jav a-pow er ed Gumb al l Mac hi ne. Fr om
t hei r ow n anal y si s t hey get f our k i nds of emai l : f an mai l f r om
c ust omer s t hat l ov e t he new 1 -i n-1 0 game, c ompl ai nt s f r om par ent s
w hose k i ds ar e addi c t ed t o t he game, r equest s t o put mac hi nes i n
new l oc at i ons, and a f ai r amount of spam.
Your task
Execution of the request isn’t guaranteed; it may fall off the end
of the chain if no object handles it (this can be an advantage or
a disadvantage).
Flyweight
Use the F ly weight Pattern when one instance of a class can be
used to prov ide many v irtual instances.
A scenario
You w ant t o add t r ees as ob jec t s i n y our new l andsc ape desi gn
appl i c at i on. In y our appl i c at i on, t r ees don’t r eal l y do v er y muc h;
t hey hav e an X-Y l oc at i on, and t hey c an dr aw t hemsel v es
dy nami c al l y , dependi ng on how ol d t hey ar e. The t hi ng i s, a user
mi ght w ant t o hav e l ot s and l ot s of t r ees i n one of t hei r home
l andsc ape desi gns. It mi ght l ook somet hi ng l i k e t hi s:
Interpreter
Use the I nterpreter Pattern to build an interpreter for a
language.
A scenario
R EL AX
The Interpreter Pattern requires some knowledge of formal grammars.
If you’ve never studied formal grammars, go ahead and read through the
pattern; you’ll still get the gist of it.
Now what?
You’v e got a gr ammar ; now al l y ou need i s a w ay t o r epr esent and
i nt er pr et sent enc es i n t he gr ammar so t hat t he st udent s c an see t he
ef f ec t s of t hei r pr ogr ammi ng on t he si mul at ed duc k s.
IN T ER PR ET ER U SES AN D D R AW B AC K S
Mediator
Use the Mediator Pattern to centralize complex
communications and control between related obj ects.
A scenario
HouseOfTheFuture’s dilemma
Mediator in action...
W i t h a Medi at or added t o t he sy st em, al l of t he appl i anc e ob jec t s
c an b e gr eat l y si mpl i f i ed:
M ED IAT O R U SES AN D D R AW B AC K S
Memento
Use the Memento Pattern when y ou need to be able to return an
obj ect to one of its prev ious states; for instance, if y our user
requests an “undo.”
A scenario
M EM EN T O B EN EF IT S
Keeping the saved state external from the key object helps to
maintain cohesion.
M EM EN T O U SES AN D D R AW B AC K S
Prototype
Use the Prototy pe Pattern when creating an instance of a giv en
class is either expensiv e or complicated.
A scenario
Your i nt er ac t i v e r ol e-pl ay i ng game has an i nsat i ab l e appet i t e f or
monst er s. A s y our her oes mak e t hei r jour ney t hr ough a
dy nami c al l y c r eat ed l andsc ape, t hey enc ount er an endl ess c hai n of
f oes t hat must b e sub dued. You’d l i k e t he monst er ’s c har ac t er i st i c s
t o ev ol v e w i t h t he c hangi ng l andsc ape. It doesn’t mak e a l ot of sense
f or b i r d-l i k e monst er s t o f ol l ow y our c har ac t er s i nt o under seas
r eal ms. Fi nal l y , y ou’d l i k e t o al l ow adv anc ed pl ay er s t o c r eat e
t hei r ow n c ust om monst er s.
PR O T O T YPE B EN EF IT S
Provides the option for the client to generate objects whose type
is not known.
PR O T O T YPE U SES AN D D R AW B AC K S
Visitor
Use the Visitor Pattern when y ou want to add capabilities to a
composite of obj ects and encapsulation is not important.
A scenario
VISIT O R B EN EF IT S
VISIT O R D R AW B AC K S
c ommand ob jec t s
enc apsul at i ng r equest s t o do somet hi ng, Cub i c l e Conv er sat i on
mappi ng, Fr om t he Di ner t o t he Command Pat t er n
usi ng, U si ng t he c ommand ob jec t
Command Pat t er n
c ommand ob jec t s
b ui l di ng, Our f i r st c ommand ob jec t
enc apsul at i ng r equest s t o do somet hi ng, Cub i c l e
Conv er sat i on
mappi ng, Fr om t he Di ner t o t he Command Pat t er n
usi ng, U si ng t he c ommand ob jec t
c ompar eTo() met hod, W e’v e got some duc k s t o sor t ...
Compl ex i t y Hi di ng Pr ox y , Desi gn Pat t er ns Cr ossw or d
c omponent s of ob jec t , The Pr i nc i pl e of Least Know l edge
Composi t e Pat t er n
c omb i ni ng pat t er ns, Duc k r euni on
def i ned, The Composi t e Pat t er n def i ned
desser t sub menu usi ng
ab out , Just w hen w e t hought i t w as saf e...
desi gni ng, Desi gni ng Menus w i t h Composi t e, Get t i ng r eady
f or a t est dr i v e...
i mpl ement i ng, Impl ement i ng MenuComponent
t est i ng, Get t i ng r eady f or a t est dr i v e...
c omposi t i on
addi ng b ehav i or at r unt i me, W el c ome t o St ar b uzz Cof f ee
f av or i ng ov er i nher i t anc e, HA S-A c an b e b et t er t han IS-A ,
W el c ome t o St ar b uzz Cof f ee
i nher i t anc e v s., Cub i c l e Conv er sat i on
ob jec t adapt er s and, Duc k Magnet s A nsw er
c onc r et e c l asses
der i v i ng f r om, A f ew gui del i nes t o hel p y ou f ol l ow t he
Pr i nc i pl e...
Fac t or y Pat t er n and, Fac t or y Met hod Pat t er n def i ned
get t i ng r i d of , Rew or k i ng t he Pi zzaSt or e c l ass
i nst ant i at i ng ob jec t s and, Look i ng at ob jec t dependenc i es
usi ng new oper at or f or i nst ant i at i ng, Bak i ng w i t h OO
Goodness: The Fac t or y Pat t er n
v ar i ab l es hol di ng r ef er enc e t o, A f ew gui del i nes t o hel p y ou
f ol l ow t he Pr i nc i pl e...
Remot e Pr ox y
ab out , Test i ng t he Moni t or
addi ng t o moni t or i ng c ode, A ddi ng a r emot e pr ox y t o t he
Gumb al l Mac hi ne moni t or i ng c ode
pr epar i ng f or r emot e ser v i c e, Get t i ng t he
Gumb al l Mac hi ne r eady t o b e a r emot e ser v i c e
r egi st er i ng w i t h RMI r egi st r y , Regi st er i ng w i t h t he RMI
r egi st r y ...
r eusi ng c l i ent f or , N ow f or t he Gumb al l Moni t or c l i ent ...
r ev i ew i ng pr oc ess, A nd now l et ’s put t he moni t or i n t he
hands of t he CEO. Hopef ul l y , t hi s t i me he’l l l ov e i t :
r ol e of , The r ol e of t he ‘r emot e pr ox y ’
t est i ng, W r i t i ng t he Moni t or t est dr i v e
w r appi ng ob jec t s and, t her e ar e no Dumb Quest i ons
Dec or at or Pat t er n
ab out , Meet t he Dec or at or Pat t er n, Test out y our new Jav a I/O
Dec or at or
A dapt er Pat t er n v s., W r i t i ng t he Enumer at i onIt er at or adapt er
c omb i ni ng pat t er ns, Duc k r euni on
def i ned, The Dec or at or Pat t er n def i ned
di sadv ant ages of , Dec or at i ng t he jav a.i o c l asses
Desi gn Pat t er ns- Reusab l e Ob jec t -Or i ent ed Sof t w ar e (Gamma et al .),
Your jour ney has just b egun...
desi gn pr i nc i pl es, The Dependenc y Inv er si on Pr i nc i pl e
depend upon ab st r ac t i ons, The Dependenc y Inv er si on
Pr i nc i pl e
Dependenc y Inv er si on Pr i nc i pl e, The Dependenc y Inv er si on
Pr i nc i pl e
Enc apsul at e w hat v ar i es, Zer oi ng i n on t he pr ob l em..., Desi gn
Pr i nc i pl e Chal l enge, Desi gn Pat t er ns Cr ossw or d, t her e ar e no
Dumb Quest i ons, The messy STA TE of t hi ngs...
Fav or c omposi t i on ov er i nher i t anc e, HA S-A c an b e b et t er t han
IS-A , Desi gn Pr i nc i pl e Chal l enge, Desi gn Pat t er ns Cr ossw or d,
The messy STA TE of t hi ngs...
One Cl ass, One Responsi b i l i t y Pr i nc i pl e, t her e ar e no Dumb
Quest i ons, The Si ngl e Responsi b i l i t y Pr i nc i pl e, Get t i ng r eady
f or a t est dr i v e...
one i nst anc e (see Si ngl et on Pat t er n)
Open-Cl osed Pr i nc i pl e, Is t he W ai t r ess r eady f or pr i me t i me?,
The messy STA TE of t hi ngs...
Pr i nc i pl e of Least Know l edge, The Pr i nc i pl e of Least
Know l edge
Pr ogr am t o an i nt er f ac e, not an i mpl ement at i on, Desi gni ng t he
Duc k Behav i or s, Desi gn Pr i nc i pl e Chal l enge, Desi gn Pat t er ns
Cr ossw or d, W hat does t hi s get us?
Si ngl e Responsi b i l i t y Pr i nc i pl e (SRP), The Si ngl e
Responsi b i l i t y Pr i nc i pl e
The Hol l y w ood Pr i nc i pl e, The Hol l y w ood Pr i nc i pl e
usi ng Ob ser v er Pat t er n, Desi gn Pr i nc i pl e Chal l enge, Desi gn
Pat t er ns Cr ossw or d
Desi gn Puzzl es
dr aw i ng c l ass di agr am mak i ng use of v i ew and c ont r ol l er , N ow
f or t he Cont r ol l er , Ex er c i se Sol ut i ons
enc apsul at i ng sub sy st em, Fac ades, t her e ar e no Dumb Quest i ons
Enumer at i on
ab out , Real -w or l d adapt er s
adapt i ng t o It er at or , A dapt i ng an Enumer at i on t o an It er at or
jav a.ut i l .Enumer at i on as ol der i mpl ement at i on of It er at or ,
Real -w or l d adapt er s, t her e ar e no Dumb Quest i ons
r emov e() met hod and, Deal i ng w i t h t he r emov e() met hod
w r i t i ng A dapt er t hat adapt s It er at or t o, W r i t i ng t he
Enumer at i onIt er at or adapt er , Desi gn Pat t er ns Cr ossw or d
ex er c i ses
Be t he JV M sol ut i on, deal i ng w i t h mul t i t hr eadi ng, BE t he JV M,
Desi gn Pat t er ns Cr ossw or d
Code Magnet s
f or Di ner Menu It er at or , Code Magnet s, Code Magnet s
Sol ut i on
f or Ob ser v er Pat t er n, Code Magnet s, Code Magnet s Sol ut i on
W ho Does W hat
mat c hi ng ob jec t s and met hods t o Command Pat t er n, Fr om
t he Di ner t o t he Command Pat t er n, Desi gn Pat t er ns
Cr ossw or d
mat c hi ng pat t er n w i t h desc r i pt i on, t her e ar e no Dumb
Quest i ons, Tool s f or y our Desi gn Tool b ox , Desi gn Pat t er ns
Cr ossw or d, Code Magnet s Sol ut i on, W e al most f or got !,
Desi gn Puzzl e Sol ut i on, t her e ar e no Dumb Quest i ons,
Desi gn Pat t er ns Cr ossw or d Sol ut i on, So y ou w anna b e a
Desi gn Pat t er ns w r i t er , Boy , i t ’s b een gr eat hav i ng y ou i n
Ob jec t v i l l e.
mat c hi ng pat t er ns w i t h i t s i nt ent , A nd now f or somet hi ng
di f f er ent ..., Desi gn Pat t er ns Cr ossw or d
f ac t or y met hod
ab out , Dec l ar i ng a f ac t or y met hod, Fac t or y Met hod Pat t er n
def i ned
as ab st r ac t , t her e ar e no Dumb Quest i ons
dec l ar i ng, Dec l ar i ng a f ac t or y met hod
Fac t or y Pat t er n
A b st r ac t Fac t or y
ab out , W hat hav e w e done?
b ui l di ng i ngr edi ent f ac t or i es, Bui l di ng t he i ngr edi ent
f ac t or i es, Desi gn Puzzl e Sol ut i on
c omb i ni ng pat t er ns, Duc k r euni on, Ex er c i se Sol ut i ons
def i ned, A b st r ac t Fac t or y Pat t er n def i ned
ex er c i se mat c hi ng desc r i pt i on of , So y ou w anna b e a Desi gn
Pat t er ns w r i t er , Boy , i t ’s b een gr eat hav i ng y ou i n
Ob jec t v i l l e.
Fac t or y Met hod Pat t er n and, A b st r ac t Fac t or y Pat t er n
def i ned
i mpl ement i ng, A b st r ac t Fac t or y Pat t er n def i ned
Si mpl e Fac t or y
ab out f ac t or y ob jec t s, Enc apsul at i ng ob jec t c r eat i on
b ui l di ng f ac t or y , Bui l di ng a si mpl e pi zza f ac t or y
def i ned, The Si mpl e Fac t or y def i ned
Fac t or y Met hod Pat t er n and, t her e ar e no Dumb Quest i ons
pat t er n honor ab l e ment i on, The Si mpl e Fac t or y def i ned
usi ng new oper at or f or i nst ant i at i ng c onc r et e c l asses,
Bak i ng w i t h OO Goodness: The Fac t or y Pat t er n
Fi r ew al l Pr ox y , The Pr ox y Zoo
Fl y w ei ght Pat t er n, Fl y w ei ght
f or l oop, Jav a’s enhanc ed f or l oop
i nst anc e v ar i ab l es, W el c ome t o St ar b uzz Cof f ee, Codi ng c ondi ment s
i nst ant i at i ng, Bak i ng w i t h OO Goodness: The Fac t or y Pat t er n,
Look i ng at ob jec t dependenc i es, One-of -a-Ki nd Ob jec t s: The
Si ngl et on Pat t er n
i nt egr at i ng Caf é Menu, usi ng It er at or Pat t er n, Tak i ng a l ook at t he
Caf é Menu
Int ent sec t i on, i n pat t er n c at al og, Look i ng mor e c l osel y at t he
Desi gn Pat t er n def i ni t i on
i nt er f ac e, Desi gni ng t he Duc k Behav i or s, Bak i ng w i t h OO Goodness:
The Fac t or y Pat t er n
i nt er f ac e t y pe, Int egr at i ng t he Duc k Behav i or s, Test i ng t he Duc k
c ode
i nt er nal i t er at or s, t her e ar e no Dumb Quest i ons
Int er pr et er Pat t er n, Int er pr et er
Int er v i ew W i t h
Composi t e Pat t er n, Get t i ng r eady f or a t est dr i v e...
Dec or at or Pat t er n, Test out y our new Jav a I/O Dec or at or
Fac t or y Met hod Pat t er n and A b st r ac t Fac t or y Pat t er n,
A b st r ac t Fac t or y Pat t er n def i ned
Si ngl et on Pat t er n, Di ssec t i ng t he c l assi c Si ngl et on Pat t er n
i mpl ement at i on
It er at or s
addi ng, A ddi ng an It er at or t o Di ner Menu
al l ow i ng dec oupl i ng, Rev i ew i ng our c ur r ent desi gn..., W hat
does t hi s get us?, The It er at or Pat t er n St r uc t ur e, Br eak f ast ,
l unc h, A N D di nner
c l eani ng up c ode usi ng jav a.ut i l .It er at or , Cl eani ng t hi ngs up
w i t h jav a.ut i l .It er at or
Col l ec t i ons and, It er at or s and Col l ec t i ons
enc apsul at i ng, Can w e enc apsul at e t he i t er at i on?
Enumer at i on adapt i ng t o, A dapt i ng an Enumer at i on t o an
It er at or , t her e ar e no Dumb Quest i ons
ex t er nal , t her e ar e no Dumb Quest i ons
HashMap and, It er at or s and Col l ec t i ons
i mpl ement i ng, Meet t he It er at or Pat t er n
i nt er nal , t her e ar e no Dumb Quest i ons
or der i ng of , t her e ar e no Dumb Quest i ons
pol y mor phi c c ode usi ng, It er at or Pat t er n def i ned, t her e ar e no
Dumb Quest i ons
usi ng Li st It t er at or , t her e ar e no Dumb Quest i ons
w r i t i ng A dapt er f or Enumer at i on, Deal i ng w i t h t he r emov e()
met hod
w r i t i ng A dapt er t hat adapt s t o Enumer at i on, W r i t i ng t he
Enumer at i onIt er at or adapt er , Desi gn Pat t er ns Cr ossw or d
mac r o c ommands
ab out , Ev er y r emot e needs a Par t y Mode!
mac r o c ommands, U si ng a mac r o c ommand, Desi gn Pat t er ns
Cr ossw or d
usi ng, U si ng a mac r o c ommand
mul t i t hr eadi ng, Can w e i mpr ov e mul t i t hr eadi ng?, Desi gn Pat t er ns
Cr ossw or d
Remot e Pr ox y
ab out , Test i ng t he Moni t or
addi ng t o moni t or i ng c ode, A ddi ng a r emot e pr ox y t o t he
Gumb al l Mac hi ne moni t or i ng c ode
pr epar i ng f or r emot e ser v i c e, Get t i ng t he
Gumb al l Mac hi ne r eady t o b e a r emot e ser v i c e
r egi st er i ng w i t h RMI r egi st r y , Regi st er i ng w i t h t he RMI
r egi st r y ...
r eusi ng c l i ent f or , N ow f or t he Gumb al l Moni t or c l i ent ...
r ev i ew i ng pr oc ess, A nd now l et ’s put t he moni t or i n t he
hands of t he CEO. Hopef ul l y , t hi s t i me he’l l l ov e i t :
r ol e of , The r ol e of t he ‘r emot e pr ox y ’
t est i ng, W r i t i ng t he Moni t or t est dr i v e
w r appi ng ob jec t s and, t her e ar e no Dumb Quest i ons
ob jec t c r eat i on, enc apsul at i ng, Enc apsul at i ng ob jec t c r eat i on,
t her e ar e no Dumb Quest i ons
ob jec t pat t er ns, Desi gn Pat t er ns, Pat t er n Cat egor i es
Ob jec t -Or i ent ed (OO) desi gn, The Dependenc y Inv er si on Pr i nc i pl e
(see al so desi gn pr i nc i pl es)
adapt er s
ab out , A dapt er s al l ar ound us
c r eat i ng Tw o W ay A dapt er s, Her e’s how t he Cl i ent uses t he
A dapt er
i n ac t i on, If i t w al k s l i k e a duc k and quac k s l i k e a duc k ,
t hen i t must mi ght b e a duc k t ur k ey w r apped w i t h a duc k
adapt er ..., Test dr i v e t he adapt er
ob jec t and c l ass ob jec t and c l ass, Ob jec t and c l ass adapt er s
ob jec t s
c omponent s of , The Pr i nc i pl e of Least Know l edge
c r eat i ng, Fac t or y Met hod Pat t er n def i ned
ob ser v er s
i n c l ass di agr am, The Ob ser v er Pat t er n: t he Cl ass Di agr am
i n Fi v e-mi nut e dr ama, Fi v e-mi nut e dr ama: a sub jec t f or
ob ser v at i on
i n Ob ser v er Pat t er n, Pub l i sher s + Sub sc r i b er s = Ob ser v er
Pat t er n
OO (Ob jec t -Or i ent ed) desi gn (see Ob jec t -Or i ent ed (OO) desi gn)
Open-Cl osed Pr i nc i pl e (OCP), Is t he W ai t r ess r eady f or pr i me t i me?,
The messy STA TE of t hi ngs...
Or gani zat i onal Pat t er ns, The Pat t er ns Zoo
ov er usi ng Desi gn Pat t er ns, Your Mi nd on Pat t er ns
Pr ot ot y pe Pat t er n, Pr ot ot y pe
pr ox i es, Cont r ol l i ng Ob jec t A c c ess: The Pr ox y Pat t er n
Pr ox y c l ass, i dent i f y i ng c l ass as, t her e ar e no Dumb Quest i ons
Pr ox y Pat t er n
A dapt er Pat t er n v s., t her e ar e no Dumb Quest i ons
Compl ex i t y Hi di ng Pr ox y , Desi gn Pat t er ns Cr ossw or d
Copy -On-W r i t e Pr ox y , Desi gn Pat t er ns Cr ossw or d
Dec or at or Pat t er n v s., t her e ar e no Dumb Quest i ons
def i ned, The Pr ox y Pat t er n def i ned
dy nami c aspec t of dy nami c pr ox i es, t her e ar e no Dumb
Quest i ons
ex er c i se mat c hi ng desc r i pt i on of , t her e ar e no Dumb
Quest i ons, So y ou w anna b e a Desi gn Pat t er ns w r i t er , Boy , i t ’s
b een gr eat hav i ng y ou i n Ob jec t v i l l e.
Fi r ew al l Pr ox y , The Pr ox y Zoo
i mpl ement at i on of Remot e Pr ox y
ab out , Test i ng t he Moni t or
addi ng t o moni t or i ng c ode, A ddi ng a r emot e pr ox y t o t he
Gumb al l Mac hi ne moni t or i ng c ode
pr epar i ng f or r emot e ser v i c e, Get t i ng t he
Gumb al l Mac hi ne r eady t o b e a r emot e ser v i c e
r egi st er i ng w i t h RMI r egi st r y , Regi st er i ng w i t h t he RMI
r egi st r y ...
r eusi ng c l i ent f or , N ow f or t he Gumb al l Moni t or c l i ent ...
r ev i ew i ng pr oc ess, A nd now l et ’s put t he moni t or i n t he
hands of t he CEO. Hopef ul l y , t hi s t i me he’l l l ov e i t :
r ol e of , The r ol e of t he ‘r emot e pr ox y ’
t est i ng, W r i t i ng t he Moni t or t est dr i v e
w r appi ng ob jec t s and, t her e ar e no Dumb Quest i ons
Remot e Pr ox y
ab out , Test i ng t he Moni t or
addi ng t o moni t or i ng c ode, A ddi ng a r emot e pr ox y t o t he
Gumb al l Mac hi ne moni t or i ng c ode
pr epar i ng f or r emot e ser v i c e, Get t i ng t he Gumb al l Mac hi ne
r eady t o b e a r emot e ser v i c e
r egi st er i ng w i t h RMI r egi st r y , Regi st er i ng w i t h t he RMI
r egi st r y ...
r eusi ng c l i ent f or , N ow f or t he Gumb al l Moni t or c l i ent ...
r ev i ew i ng pr oc ess, A nd now l et ’s put t he moni t or i n t he hands
of t he CEO. Hopef ul l y , t hi s t i me he’l l l ov e i t :
r ol e of , The r ol e of t he ‘r emot e pr ox y ’
t est i ng, W r i t i ng t he Moni t or t est dr i v e
w r appi ng ob jec t s and, t her e ar e no Dumb Quest i ons
Sub jec t
i n c l ass di agr am, The Ob ser v er Pat t er n: t he Cl ass Di agr am
i n Fi v e-mi nut e dr ama, Fi v e-mi nut e dr ama: a sub jec t f or
ob ser v at i on
i n Ob ser v er Pat t er n, Pub l i sher s + Sub sc r i b er s = Ob ser v er
Pat t er n
undo c ommands
c r eat i ng, Ti me t o w r i t e t hat doc ument at i on..., U si ng a mac r o
c ommand
i mpl ement i ng f or mac r o c ommand, U si ng a mac r o c ommand
suppor t of , Ti me t o w r i t e t hat doc ument at i on...
t est i ng, Ti me t o QA t hat U ndo b ut t on!, Get r eady t o t est t he
c ei l i ng f an
usi ng st at e t o i mpl ement , U si ng st at e t o i mpl ement U ndo
v ar i ab l es
dec l ar i ng b ehav i or , Int egr at i ng t he Duc k Behav i or s
hol di ng r ef er enc e t o c onc r et e c l ass, A f ew gui del i nes t o hel p
y ou f ol l ow t he Pr i nc i pl e...
i nst anc e, W el c ome t o St ar b uzz Cof f ee, Codi ng c ondi ment s
V i si t or Pat t er n, V i si t or
V l i ssi des, John, Cr ui si n’ Ob jec t v i l l e w i t h t he Gang of Four
v ol at i l e k ey w or d, 3. U se “doub l e-c hec k ed l oc k i ng” t o r educ e t he use
of sy nc hr oni zat i on i n get Inst anc e().
w eat her st at i on
b ui l di ng di spl ay el ement s, N ow , l et ’s b ui l d t hose di spl ay
el ement s
desi gni ng, Desi gni ng t he W eat her St at i on
i mpl ement i ng, Impl ement i ng t he W eat her St at i on
pow er i ng up, Pow er up t he W eat her St at i on