50% found this document useful (2 votes)
1K views355 pages

(Head First Series) Eric Freeman - Elisabeth Robson - Head First Design Patterns - Building Extensible and Maintainable Object-Oriented Software (2021, O'Reilly Media) - Libgen - Li

Uploaded by

testesteteste
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
50% found this document useful (2 votes)
1K views355 pages

(Head First Series) Eric Freeman - Elisabeth Robson - Head First Design Patterns - Building Extensible and Maintainable Object-Oriented Software (2021, O'Reilly Media) - Libgen - Li

Uploaded by

testesteteste
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 355

1 .

Cr eat or s of t he Head Fi r st Ser i es


2. Tab l e of Cont ent s (t he r eal t hi ng)
3. Int r o: How t o use t hi s Book

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 ?

b . W e k now w hat y ou’r e t hi nk i ng.


c . A nd w e k now w hat y our b r ai n i s t hi nk i ng.
d. Met ac ogni t i on: t hi nk i ng ab out t hi nk i ng
e. Her e’s w hat W E di d:
f . Her e’s w hat YOU c an do t o b end y our b r ai n i nt o
sub mi ssi on
g. Read Me

i . W e use si mpl e U ML-l i k e di agr ams.


i i . W e don’t c ov er ev er y si ngl e Desi gn
Pat t er n ev er c r eat ed.
i i i . The ac t i v i t i es ar e N OT opt i onal .
i v . W e use t he w or d “c omposi t i on” i n t he
gener al OO sense, w hi c h i s mor e
f l ex i b l e t han t he st r i c t U ML use of
“c omposi t i on.”
v . The r edundanc y i s i nt ent i onal and
i mpor t ant .
v i . The c ode ex ampl es ar e as l ean as
possi b l e.
v i i . The Br ai n Pow er ex er c i ses don’t hav e
answ er s.

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 . Fr om t he sec ond edi t i on


i i . V er y Spec i al Thank s

4. 1 . W el c ome t o Desi gn Pat t er ns: Int r o t o Desi gn Pat t er ns

a. It st ar t ed w i t h a si mpl e Si mU Duc k app


b . But now w e need t he duc k s t o FLY
c . But somet hi ng w ent hor r i b l y w r ong...
d. Joe t hi nk s ab out i nher i t anc e...
e. How ab out an i nt er f ac e?
f . W hat w oul d y ou do i f y ou w er e Joe?
g. The one c onst ant i n sof t w ar e dev el opment
h. Zer oi ng i n on t he pr ob l em...
i . Separ at i ng w hat c hanges f r om w hat st ay s t he
same
j. Desi gni ng t he Duc k Behav i or s
k . Impl ement i ng t he Duc k Behav i or s
l . t her e ar e no Dumb Quest i ons
m. Int egr at i ng t he Duc k Behav i or s
n. Mor e i nt egr at i on...
o. Test i ng t he Duc k c ode
p. Set t i ng b ehav i or dy nami c al l y
q. The Bi g Pi c t ur e on enc apsul at ed b ehav i or s
r . HA S-A c an b e b et t er t han IS-A
s. Speak i ng of Desi gn Pat t er ns...
t . Desi gn Puzzl e
u. Ov er hear d at t he l oc al di ner ...
v . Ov er hear d i n t he nex t c ub i c l e...
w . The pow er of a shar ed pat t er n v oc ab ul ar y
x . How do I use Desi gn Pat t er ns?
y . t her e ar e no Dumb Quest i ons
z. Tool s f or y our Desi gn Tool b ox
aa. Desi gn Pat t er ns Cr ossw or d
ab . Desi gn Puzzl e Sol ut i on
ac . Desi gn Pat t er ns Cr ossw or d Sol ut i on

5. 2. Keepi ng y our Ob jec t s i n t he Know : The Ob ser v er


Pat t er n

a. The W eat her Moni t or i ng appl i c at i on ov er v i ew


b . U npac k i ng t he W eat her Dat a c l ass
c . Our Goal
d. St r et c h Goal
e. Tak i ng a f i r st , mi sgui ded i mpl ement at i on of t he
W eat her St at i on
f . W hat ’s w r ong w i t h our i mpl ement at i on
any w ay ?
g. Meet t he Ob ser v er Pat t er n
h. Pub l i sher s + Sub sc r i b er s = Ob ser v er Pat t er n
i . A day i n t he l i f e of t he Ob ser v er Pat t er n
j. Fi v e-mi nut e dr ama: a sub jec t f or ob ser v at i on
k . Tw o w eek s l at er ...
l . The Ob ser v er Pat t er n def i ned
m. The Ob ser v er Pat t er n: t he Cl ass Di agr am
n. t her e ar e no Dumb Quest i ons
o. The Pow er of Loose Coupl i ng
p. Cub i c l e c onv er sat i on
q. Desi gni ng t he W eat her St at i on
r . Impl ement i ng t he W eat her St at i on
s. Impl ement i ng t he Sub jec t i nt er f ac e i n
W eat her Dat a
t . N ow , l et ’s b ui l d t hose di spl ay el ement s
u. t her e ar e no Dumb Quest i ons
v . Pow er up t he W eat her St at i on
w . Look i ng f or t he Ob ser v er Pat t er n i n t he W i l d

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

x . Codi ng t he l i f e-c hangi ng appl i c at i on


y . t her e ar e no Dumb Quest i ons
z. Meanw hi l e, b ac k at W eat her -O-Rama

i . For t he Sub jec t t o send not i f i c at i ons...


i i . For an Ob ser v er t o r ec ei v e
not i f i c at i ons...

aa. Code Magnet s

ab . Test Dr i v e t he new c ode


ac . Tool s f or y our Desi gn Tool b ox
ad. Desi gn Pr i nc i pl e Chal l enge
ae. Desi gn Pat t er ns Cr ossw or d
af . Desi gn Pr i nc i pl e Chal l enge Sol ut i on
ag. Code Magnet s Sol ut i on
ah. Desi gn Pat t er ns Cr ossw or d Sol ut i on

6. 3. Dec or at i ng Ob jec t s: The Dec or at or Pat t er n

a. W el c ome t o St ar b uzz Cof f ee


b . The Open-Cl osed Pr i nc i pl e
c . t her e ar e no Dumb Quest i ons
d. Meet t he Dec or at or Pat t er n
e. Const r uc t i ng a dr i nk or der w i t h Dec or at or s

i . Ok ay , her e’s w hat w e k now ab out


Dec or at or s, so f ar ...

f . The Dec or at or Pat t er n def i ned

g. Dec or at i ng our Bev er ages


h. Cub i c l e Conv er sat i on
i . N ew b ar i st a t r ai ni ng
j. W r i t i ng t he St ar b uzz c ode
k . Codi ng b ev er ages
l . Codi ng c ondi ment s
m. Ser v i ng some c of f ees
n. t her e ar e no Dumb Quest i ons
o. Real -W or l d Dec or at or s: Jav a I/O
p. Dec or at i ng t he jav a.i o c l asses
q. W r i t i ng y our ow n Jav a I/O Dec or at or
r . Test out y our new Jav a I/O Dec or at or
s. Tool s f or y our Desi gn Tool b ox

7 . 4. Bak i ng w i t h OO Goodness: The Fac t or y Pat t er n

a. Ident i f y i ng t he aspec t s t hat v ar y


b . But t he pr essur e i s on t o add mor e pi zza t y pes
c . Enc apsul at i ng ob jec t c r eat i on
d. Bui l di ng a si mpl e pi zza f ac t or y
e. t her e ar e no Dumb Quest i ons
f . Rew or k i ng t he Pi zzaSt or e c l ass
g. The Si mpl e Fac t or y def i ned
h. Fr anc hi si ng t he pi zza st or e

i . W e’v e seen one appr oac h...


i i . But y ou’d l i k e a l i t t l e mor e qual i t y
c ont r ol ...

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

i . Let ’s see how i t w or k s: or der i ng pi zzas


w i t h t he pi zza f ac t or y met hod
i i . So how do t hey or der ?
i i i . Let ’s c hec k out how t hese pi zzas ar e
r eal l y made t o or der ...

m. W e’r e just mi ssi ng one t hi ng: Pi zzas!


i . Our Pi zza St or e i sn’t goi ng t o b e v er y
popul ar w i t hout some pi zzas, so l et ’s
i mpl ement t hem
i i . N ow w e just need some c onc r et e
sub c l asses...how ab out def i ni ng N ew
Yor k and Chi c ago-st y l e c heese pi zzas?

n. You’v e w ai t ed l ong enough. Ti me f or some


pi zzas!
o. It ’s f i nal l y t i me t o meet t he Fac t or y Met hod
Pat t er n

i . The Cr eat or c l asses


i i . The Pr oduc t c l asses

p. V i ew Cr eat or s and Pr oduc t s i n Par al l el


q. Desi gn Puzzl e
r . Fac t or y Met hod Pat t er n def i ned
s. t her e ar e no Dumb Quest i ons
t . Look i ng at ob jec t dependenc i es
u. The Dependenc y Inv er si on Pr i nc i pl e
v . A ppl y i ng t he Pr i nc i pl e
w . Inv er t i ng y our t hi nk i ng...
x . 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...
y . Meanw hi l e, b ac k at t he Pi zza St or e...

i . Ensur i ng c onsi st enc y i n y our


i ngr edi ent s

z. Fami l i es of i ngr edi ent s...


aa. Bui l di ng t he i ngr edi ent f ac t or i es
ab . Bui l di ng t he N ew Yor k i ngr edi ent f ac t or y
ac . Rew or k i ng t he pi zzas...
ad. Rew or k i ng t he pi zzas, c ont i nued...
ae. Rev i si t i ng our pi zza st or es
af . W hat hav e w e done?
ag. Mor e pi zza f or Et han and Joel ...

i . Et han and Joel c an’t get enough


Ob jec t v i l l e Pi zza! W hat t hey don’t
k now i s t hat now t hei r or der s ar e
mak i ng use of t he new i ngr edi ent
f ac t or i es. So now w hen t hey or der ...
i i . Fr om her e t hi ngs c hange, b ec ause w e
ar e usi ng an i ngr edi ent f ac t or y

ah. A b st r ac t Fac t or y Pat t er n def i ned


ai . Fac t or y Met hod and A b st r ac t Fac t or y c ompar ed
aj. Tool s f or y our Desi gn Tool b ox
ak . Desi gn Pat t er ns Cr ossw or d
al . Desi gn Puzzl e Sol ut i on
am. Desi gn Pat t er ns Cr ossw or d Sol ut i on

8. 5. One-of -a-Ki nd Ob jec t s: The Si ngl et on Pat t er n

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

b . 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
c . The Choc ol at e Fac t or y
d. Si ngl et on Pat t er n def i ned
e. Her shey , PA , w e hav e a pr ob l em...
f . BE t he JV M
g. Deal i ng w i t h mul t i t hr eadi ng
h. Can w e i mpr ov e mul t i t hr eadi ng?

i . 1 . Do not hi ng i f t he per f or manc e of


get Inst anc e() i sn’t c r i t i c al t o y our
appl i c at i on.
i i . 2. Mov e t o an eager l y c r eat ed i nst anc e
r at her t han a l azi l y c r eat ed one.
i i i . 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().

i . Meanw hi l e, b ac k at t he Choc ol at e Fac t or y ...


j. Congr at ul at i ons!
k . t her e ar e no Dumb Quest i ons
l . Tool s f or y our Desi gn Tool b ox
m. Desi gn Pat t er ns Cr ossw or d
n. Desi gn Pat t er ns Cr ossw or d Sol ut i on

9. 6. Enc apsul at i ng Inv oc at i on: The Command Pat t er n

a. Home A ut omat i on or Bust , Inc .


b . Fr ee har dw ar e! Let ’s c hec k out t he Remot e
Cont r ol ...
c . Tak i ng a l ook at t he v endor c l asses
d. Cub i c l e Conv er sat i on
e. Meanw hi l e, b ac k at t he Di ner ..., or , A b r i ef
i nt r oduc t i on t o t he Command Pat t er n
f . Let ’s st udy t he i nt er ac t i on i n a l i t t l e mor e
det ai l ...
g. The Ob jec t v i l l e Di ner r ol es and
r esponsi b i l i t i es
h. Fr om t he Di ner t o t he Command Pat t er n
i . Our f i r st c ommand ob jec t
j. U si ng t he c ommand ob jec t
k . Cr eat i ng a si mpl e t est t o use t he Remot e Cont r ol
l . The Command Pat t er n def i ned
m. The Command Pat t er n def i ned: t he c l ass di agr am

n. A ssi gni ng Commands t o sl ot s


o. Impl ement i ng t he Remot e Cont r ol
p. Impl ement i ng t he Commands
q. Put t i ng t he Remot e Cont r ol t hr ough i t s pac es

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 ...

r . Ti me t o w r i t e t hat doc ument at i on...


s. W hat ar e w e doi ng?
t . Ti me t o QA t hat U ndo b ut t on!

u. U si ng st at e t o i mpl ement U ndo


v . A ddi ng U ndo t o t he Cei l i ng Fan c ommands
w . Get r eady t o t est t he c ei l i ng f an
x . Test i ng t he c ei l i ng f an...
y . Ev er y r emot e needs a Par t y Mode!
z. U si ng a mac r o c ommand
aa. t her e ar e no Dumb Quest i ons
ab . Mor e uses of t he Command Pat t er n: queui ng
r equest s
ac . Mor e uses of t he Command Pat t er n: l oggi ng
r equest s
ad. Command Pat t er n i n t he Real W or l d
ae. Tool s f or y our Desi gn Tool b ox
af . Desi gn Pat t er ns Cr ossw or d

1 0. 7 . Bei ng A dapt i v e: The A dapt er and Fac ade Pat t er ns

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 . Her e’s how t he Cl i ent uses t he


A dapt er

f . t her e ar e no Dumb Quest i ons


g. A dapt er Pat t er n def i ned
h. Ob jec t and c l ass adapt er s
i . Duc k Magnet s
j. Duc k Magnet s A nsw er
k . Real -w or l d adapt er s

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 . Desi gni ng t he A dapt er


i i . Deal i ng w i t h t he r emov e() met hod
i i i . W r i t i ng t he Enumer at i onIt er at or
adapt er

m. A nd now f or somet hi ng di f f er ent ...


n. Home Sw eet Home Theat er
o. W at c hi ng a mov i e (t he har d w ay )
p. Li ght s, Camer a, Fac ade!
q. t her e ar e no Dumb Quest i ons
r . Const r uc t i ng y our home t heat er f ac ade
s. Impl ement i ng t he si mpl i f i ed i nt er f ac e
t . Ti me t o w at c h a mov i e (t he easy w ay )
u. Fac ade Pat t er n def i ned
v . The Pr i nc i pl e of Least Know l edge
w . How N OT t o W i n Fr i ends and Inf l uenc e Ob jec t s

i . Keepi ng y our met hod c al l s i n b ounds...

x . t her e ar e no Dumb Quest i ons


y . The Fac ade Pat t er n and t he Pr i nc i pl e of Least
Know l edge
z. Tool s f or y our Desi gn Tool b ox
aa. Desi gn Pat t er ns Cr ossw or d
ab . Desi gn Pat t er ns Cr ossw or d Sol ut i on

1 1 . 8. Enc apsul at i ng A l gor i t hms: The Templ at e Met hod


Pat t er n
a. It ’s t i me f or some mor e c af f ei ne
b . W hi ppi ng up some c of f ee and t ea c l asses (i n
Jav a)
c . A nd now t he Tea...
d. Let ’s ab st r ac t t hat Cof f ee and Tea
e. Tak i ng t he desi gn f ur t her ...
f . A b st r ac t i ng pr epar eRec i pe()
g. W hat hav e w e done?
h. Meet t he Templ at e Met hod

i . Let ’s mak e some t ea...


j. W hat di d t he Templ at e Met hod get us?
k . Templ at e Met hod Pat t er n def i ned
l . Hook ed on Templ at e Met hod...
m. U si ng t he hook
n. Let ’s r un t he Test Dr i v e

i . A nd l et ’s gi v e i t a r un...

o. t her e ar e no Dumb Quest i ons

p. The Hol l y w ood Pr i nc i pl e


q. The Hol l y w ood Pr i nc i pl e and Templ at e Met hod
r . t her e ar e no Dumb Quest i ons
s. Templ at e Met hods i n t he W i l d
t . Sor t i ng w i t h Templ at e Met hod
u. W e’v e got some duc k s t o sor t ...
v . W hat i s c ompar eTo()?
w . Compar i ng Duc k s and Duc k s
x . Let ’s sor t some Duc k s

i . Let t he sor t i ng c ommenc e!

y . The mak i ng of t he sor t i ng duc k mac hi ne


z. t her e ar e no Dumb Quest i ons
aa. Sw i ngi n’ w i t h Fr ames
ab . Cust om Li st s w i t h A b st r ac t Li st
ac . Desi gn Pat t er ns Cr ossw or d
ad. Tool s f or y our Desi gn Tool b ox
ae. Desi gn Pat t er ns Cr ossw or d Sol ut i on

1 2. 9. W el l -Managed Col l ec t i ons: The It er at or and Composi t e


Pat t er ns

a. Br eak i ng N ew s: Ob jec t v i l l e Di ner and


Ob jec t v i l l e Panc ak e House Mer ge
b . Chec k out t he Menu It ems
c . Lou and Mel ’s Menu i mpl ement at i ons
d. W hat ’s t he pr ob l em w i t h hav i ng t w o di f f er ent
menu r epr esent at i ons?

i . The Jav a-Enab l ed W ai t r ess


Spec i f i c at i on

e. Impl ement i ng t he spec : our f i r st at t empt


f . W hat now ?
g. Can w e enc apsul at e t he i t er at i on?
h. Meet t he It er at or Pat t er n
i . A ddi ng an It er at or t o Di ner Menu
j. Rew or k i ng t he Di ner Menu w i t h It er at or
k . Fi x i ng up t he W ai t r ess c ode
l . Test i ng our c ode

i . Her e’s t he t est r un...

m. W hat hav e w e done so f ar ?


n. Rev i ew i ng our c ur r ent desi gn...
o. Mak i ng some i mpr ov ement s...
p. t her e ar e no Dumb Quest i ons
q. Cl eani ng t hi ngs up w i t h jav a.ut i l .It er at or
r . W e ar e al most t her e...
s. W hat does t hi s get us?
t . It er at or Pat t er n def i ned
u. The It er at or Pat t er n St r uc t ur e
v . The Si ngl e Responsi b i l i t y Pr i nc i pl e
w . t her e ar e no Dumb Quest i ons
x . Meet Jav a’s It er ab l e i nt er f ac e
y . Jav a’s enhanc ed f or l oop
z. N ot so f ast ; A r r ay s ar e not It er ab l es

aa. Tak i ng a l ook at t he Caf é Menu


ab . Rew or k i ng t he Caf é Menu c ode
ac . A ddi ng t he Caf e Menu t o t he W ai t r ess
ad. Br eak f ast , l unc h, A N D di nner

i . Her e’s t he t est r un; c hec k out t he new


di nner menu f r om t he Caf é!

ae. W hat di d w e do?


af . W e dec oupl ed t he W ai t r ess....
ag. ...and w e made t he W ai t r ess mor e ex t ensi b l e
ah. But t her e’s mor e!
ai . It er at or s and Col l ec t i ons
aj. Code Magnet s
ak . Is t he W ai t r ess r eady f or pr i me t i me?
al . Just w hen w e t hought i t w as saf e...
am. W hat do w e need?
an. The Composi t e Pat t er n def i ned
ao. t her e ar e no Dumb Quest i ons
ap. Desi gni ng Menus w i t h Composi t e
aq. Impl ement i ng MenuComponent
ar . Impl ement i ng t he MenuIt em
as. Impl ement i ng t he Composi t e Menu

i . Fi x i ng t he pr i nt () met hod

at . Get t i ng r eady f or a t est dr i v e...


au. N ow f or t he t est dr i v e...
av . Get t i ng r eady f or a t est dr i v e...
aw . Desi gn Pat t er ns Cr ossw or d

ax . Tool s f or y our Desi gn Tool b ox


ay . Code Magnet s Sol ut i on
az. Desi gn Pat t er ns Cr ossw or d Sol ut i on

1 3. 1 0. The St at e of Thi ngs: The St at e Pat t er n

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

t . Demo f or t he CEO of Mi ght y Gumb al l , Inc .


u. t her e ar e no Dumb Quest i ons
v . Sani t y c hec k ...
w . W e al most f or got !
x . Tool s f or y our Desi gn Tool b ox
y . Desi gn Puzzl e Sol ut i on

1 4. 1 1 . Cont r ol l i ng Ob jec t A c c ess: The Pr ox y Pat t er n

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 ’

c . 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
d. Remot e met hods 1 01

i . W al k i ng t hr ough t he desi gn

e. How t he met hod c al l happens


f . Jav a RMI, t he Bi g Pi c t ur e
g. Mak i ng t he Remot e ser v i c e
h. St ep one: mak e a Remot e i nt er f ac e
i . St ep t w o: mak e a Remot e i mpl ement at i on
j. St ep f our : st ar t t he ser v i c e
k . St ep f our : st ar t t he ser v i c e
l . t her e ar e no Dumb Quest i ons
m. Compl et e c ode f or t he ser v er si de
n. Compl et e c ode f or t he c l i ent si de
o. Bac k t o our Gumb al l Mac hi ne r emot e pr ox y
p. 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
q. Regi st er i ng w i t h t he RMI r egi st r y ...
r . N ow f or t he Gumb al l Moni t or c l i ent ...
s. W r i t i ng t he Moni t or t est dr i v e
t . A not her demo f or t he CEO of Mi ght y Gumb al l ...

i . 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 :

u. The Pr ox y Pat t er n def i ned


v . Get r eady f or t he V i r t ual Pr ox y
i . Remot e Pr ox y
i i . V i r t ual Pr ox y

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

i . How ImagePr ox y i s goi ng t o w or k :

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

i . Thi ngs t o t r y ...

aa. W hat di d w e do?


ab . t her e ar e no Dumb Quest i ons
ac . U si ng t he Jav a A PI’s Pr ox y t o c r eat e a
pr ot ec t i on pr ox y
ad. Geek y Mat c hmak i ng i n Ob jec t v i l l e
ae. The Per son i mpl ement at i on
af . Fi v e-mi nut e dr ama: pr ot ec t i ng sub jec t s
ag. 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
ah. St ep one: c r eat i ng Inv oc at i on Handl er s
ai . Cr eat i ng Inv oc at i on Handl er s, c ont i nued...
aj. St ep t w o: c r eat i ng t he Pr ox y c l ass and
i nst ant i at i ng t he Pr ox y ob jec t
ak . Test i ng t he mat c hmak i ng ser v i c e
al . Runni ng t he c ode...
am. t her e ar e no Dumb Quest i ons
an. The Pr ox y Zoo
ao. Desi gn Pat t er ns Cr ossw or d
ap. Tool s f or y our Desi gn Tool b ox
aq. Desi gn Pat t er ns Cr ossw or d Sol ut i on
ar . The c ode f or t he A l b um Cov er V i ew er

1 5. 1 2. Pat t er ns of Pat t er ns: Compound Pat t er ns

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...

g. Meet Model -V i ew -Cont r ol l er


h. A c l oser l ook ...
i . t her e ar e no Dumb Quest i ons
j. U nder st andi ng MV C as a set of Pat t er ns
k . Ob ser v er
l . St r at egy
m. Composi t e
n. U si ng MV C t o c ont r ol t he b eat ...

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 ...

o. Put t i ng t he pi ec es t oget her


p. Bui l di ng t he pi ec es

i . Let ’s c hec k out t he


Beat Model Int er f ac e b ef or e l ook i ng at
t he i mpl ement at i on:

q. N ow l et ’s hav e a l ook at t he c onc r et e Beat Model


c l ass
r . The V i ew
s. Impl ement i ng t he V i ew
t . N ow f or t he Cont r ol l er

i . A nd her e’s t he i mpl ement at i on of t he


c ont r ol l er :

u. Put t i ng i t al l t oget her ...

i . A nd now f or a t est r un...


i i . Thi ngs t o t r y

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...

y . A nd now f or a t est r un...

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

i . The Beat Model


i i . The V i ew
i i i . The Cont r ol l er
i v . The Hear t Model
v . The Hear t A dapt er
v i . The Cont r ol l er

1 6. 1 3. Pat t er ns i n t he Real W or l d: Bet t er Li v i ng w i t h


Pat t er ns

a. Desi gn Pat t er n def i ned


b . Look i ng mor e c l osel y at t he Desi gn Pat t er n
def i ni t i on
c . t her e ar e no Dumb Quest i ons
d. So y ou w anna b e a Desi gn Pat t er ns w r i t er
e. Or gani zi ng Desi gn Pat t er ns
f . Pat t er n Cat egor i es
g. Thi nk i ng i n Pat t er ns

i . Keep i t si mpl e (KISS)


i i . Desi gn Pat t er ns ar en’t a magi c b ul l et ;
i n f ac t , t hey ’r e not ev en a b ul l et !
i i i . You k now y ou need a pat t er n w hen...
i v . Ref ac t or i ng t i me i s Pat t er ns t i me!
v . Tak e out w hat y ou don’t r eal l y need.
Don’t b e af r ai d t o r emov e a Desi gn
Pat t er n f r om y our desi gn.
v i . If y ou don’t need i t now , don’t do i t
now .

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...

i . The def i ni t i v e Desi gn Pat t er ns t ex t


i i . The def i ni t i v e Pat t er ns t ex t s
i i i . Ot her Desi gn Pat t er ns r esour c es

l . The Pat t er ns Zoo


m. A nni hi l at i ng ev i l w i t h A nt i -Pat t er ns
n. Tool s f or y our Desi gn Tool b ox
o. Leav i ng Ob jec t v i l l e...
p. Boy , i t ’s b een gr eat hav i ng y ou i n Ob jec t v i l l e.

1 7 . A . Lef t ov er Pat t er ns

a. Br i dge

i . Your di l emma

b . W hy use t he Br i dge Pat t er n?


c . Bui l der

i . You need a f l ex i b l e desi gn

d. W hy use t he Bui l der Pat t er n?


e. Chai n of Responsi b i l i t y

i . A sc enar i o
i i . Your t ask

f . How t o use t he Chai n of Responsi b i l i t y Pat t er n


g. Fl y w ei ght

i . A sc enar i o
i i . Your b i g c l i ent ’s di l emma

h. W hy use t he Fl y w ei ght Pat t er n?


i . Int er pr et er

i . A sc enar i o
i i . N ow w hat ?

j. How t o i mpl ement an i nt er pr et er


k . Medi at or

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

b y Er i c Fr eeman, El i sab et h Rob son, Kat hy Si er r a, and Ber t Bat es

Copy r i ght © 2021 Er i c Fr eeman and El i sab et h Rob son. A l l r i ght s


r eser v ed.

Pr i nt ed i n Canada.

Pub l i shed b y O’Rei l l y Medi a, Inc ., 1 005 Gr av enst ei n Hi ghw ay


N or t h, Seb ast opol , CA 9547 2.

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 .

Editors 1st Edition: Mi k e Hendr i c k son, Mi k e Louk i des

Editors 2nd Edition: Mi c hel e Cr oni n, Mel i ssa Duf f i el d

Cov er Designer: El l i e V ol c k hausen

Pattern Wranglers: Er i c Fr eeman, El i sab et h Rob son

Printing History :

Oc t ob er 2004: Fi r st edi t i on

Dec emb er 2020: Sec ond edi t i on

Release History :

2020-1 1 -1 0 Fi r st r el ease

The O’Rei l l y l ogo i s a r egi st er ed t r ademar k of O’Rei l l y Medi a, Inc .


Jav a and al l Jav a-b ased t r ademar k s and l ogos ar e t r ademar k s or
r egi st er ed t r ademar k s of Sun Mi c r osy st ems, Inc ., i n t he U ni t ed
St at es and ot her c ount r i es. O’Rei l l y Medi a, Inc . i s i ndependent of
Sun Mi c r osy st ems.

Many of t he desi gnat i ons used b y manuf ac t ur er s and sel l er s t o


di st i ngui sh t hei r pr oduc t s ar e c l ai med as t r ademar k s.

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.

W hi l e ev er y pr ec aut i on has b een t ak en i n t he pr epar at i on of t hi s


b ook , t he pub l i sher and t he aut hor s assume no r esponsi b i l i t y f or
er r or s or omi ssi ons, or f or damages r esul t i ng f r om t he use of t he
i nf or mat i on c ont ai ned her ei n.

In ot her w or ds, i f y ou use any t hi ng i n Head Firs t Des ign Patterns t o,


say , r un a nuc l ear pow er pl ant , y ou’r e on y our ow n. W e do,
how ev er , enc our age y ou t o use t he DJ V i ew app.

N o duc k s w er e har med i n t he mak i ng of t hi s b ook .

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.

ISBN : 97 8-1 -492-07 800-5


[MBP]
To t he Gang of Four , w hose i nsi ght and ex per t i se i n c apt ur i ng and
c ommuni c at i ng Desi gn Pat t er ns has c hanged t he f ac e of sof t w ar e
desi gn f or ev er , and b et t er ed t he l i v es of dev el oper s t hr oughout t he
w or l d.

But s erious ly , w hen ar e w e goi ng t o see a sec ond edi t i on? A f t er al l ,


i t ’s b een onl y tw enty -fiv e y ears .
Authors of Head First Design
Patterns

Eric i s desc r i b ed b y Head Fi r st ser i es c o-c r eat or Kat hy Si er r a as


“one of t hose r ar e i ndi v i dual s f l uent i n t he l anguage, pr ac t i c e, and
c ul t ur e of mul t i pl e domai ns f r om hi pst er hac k er , c or por at e V P,
engi neer , t hi nk t ank .”

By t r ai ni ng, Er i c i s a c omput er sc i ent i st , hav i ng ear ned hi s PhD at


Yal e U ni v er si t y . Pr of essi onal l y , Er i c w as f or mer l y CTO of Di sney
Onl i ne & Di sney .c om (http://Disney.com) at t he W al t Di sney Company .

Er i c now c o-di r ec t s t he Head Fi r st ser i es and dev ot es hi s t i me t o


c r eat i ng pr i nt and v i deo c ont ent at W i c k edl y Smar t , w hi c h i s
di st r i b ut ed ac r oss t he l eadi ng educ at i onal c hannel s.

Er i c ’s Head Fi r st t i t l es i nc l ude Head Firs t Des ign Patterns , Head


Firs t HTML & CS S , Head Firs t Jav aS c ript Program m ing, Head Firs t
HTML5 Program m ing, and Head Firs t Learn to Code.

Er i c l i v es i n A ust i n, Tex as.

Elisabeth i s a sof t w ar e engi neer , w r i t er , and t r ai ner . She has b een


passi onat e ab out t ec hnol ogy si nc e her day s as a st udent at Yal e
U ni v er si t y , w her e she ear ned a Mast er s of Sc i enc e i n Comput er
Sc i enc e.

She’s c ur r ent l y c of ounder of W i c k edl y Smar t , w her e she c r eat es


b ook s, ar t i c l es, v i deos, and mor e. Pr ev i ousl y , as Di r ec t or of Spec i al
Pr ojec t s at O’Rei l l y Medi a, El i sab et h pr oduc ed i n-per son
w or k shops and onl i ne c our ses on a v ar i et y of t ec hni c al t opi c s and
dev el oped her passi on f or c r eat i ng l ear ni ng ex per i enc es t o hel p
peopl e under st and t ec hnol ogy .

W hen not i n f r ont of her c omput er , y ou’l l f i nd El i sab et h hi k i ng,


c y c l i ng, k ay ak i ng, and gar deni ng i n t he gr eat out door s, of t en w i t h
her c amer a near b y .
Creators of the Head First Series

Kathy has b een i nt er est ed i n l ear ni ng t heor y si nc e her day s as a


game desi gner f or V i r gi n, MGM, and A mb l i n’, and a t eac her of N ew
Medi a A ut hor i ng at U CLA . She w as a mast er Jav a t r ai ner f or Sun
Mi c r osy st ems, and she f ounded Jav aRanc h.c om (http://JavaRanch.com)
(now CodeRanc h.c om (http://CodeRanch.com) ), w hi c h w on Jol t Col a
Pr oduc t i v i t y aw ar ds i n 2003 and 2004.

In 201 5, she w on t he El ec t r oni c Fr ont i er Foundat i on’s Pi oneer


A w ar d f or her w or k c r eat i ng sk i l l f ul user s and b ui l di ng
sust ai nab l e c ommuni t i es.

Kat hy ’s r ec ent f oc us has b een on c ut t i ng-edge, mov ement sc i enc e


and sk i l l ac qui si t i on c oac hi ng, k now n as ec ol ogi c al dy nami c s or
“Ec o-D.” Her w or k usi ng Ec o-D f or t r ai ni ng hor ses i s usher i ng i n a
f ar , f ar mor e humane appr oac h t o hor semanshi p, c ausi ng del i ght
f or some (and sadl y , c onst er nat i on f or ot her s). Those f or t unat e
(aut onomous!) hor ses w hose ow ner s ar e usi ng Kat hy ’s appr oac h ar e
happi er , heal t hi er , and mor e at hl et i c t han t hei r f el l ow s w ho ar e
t r adi t i onal l y t r ai ned.

You c an f ol l ow Kat hy on Inst agr am: @pant her f l ow s.

Bef or e Bert w as an aut hor , he w as a dev el oper , spec i al i zi ng i n ol d-


sc hool A I (most l y ex per t sy st ems), r eal -t i me OSes, and c ompl ex
sc hedul i ng sy st ems.

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 .

Ber t ’s a Go pl ay er , and i n 201 6 he w at c hed i n hor r or and f asc i nat i on


as A l phaGo t r ounc ed Lee Sedol . Rec ent l y he’s b een usi ng Ec o-D
(ec ol ogi c al dy nami c s) t o i mpr ov e hi s gol f game and t o t r ai n hi s
par r ot l et Bok eh.

Ber t and Kat hy hav e b een pr i v i l eged t o k now Bet h and Er i c f or 1 6


y ear s now , and t he Head Fi r st ser i es i s ex t r emel y f or t unat e t o
c ount t hem as k ey c ont r i b ut or s.

You c an send Ber t a message at CodeRanc h.c om (http://CodeRanch.com) .


Table of Contents (the real thing)
I ntro

Y our brain on Design Patterns. Her e y ou ar e t r y i ng t o


learn somet hi ng, w hi l e her e y our brain i s doi ng y ou a
f av or b y mak i ng sur e t he l ear ni ng doesn’t s tic k . Your
b r ai n’s t hi nk i ng, “Bet t er l eav e r oom f or mor e i mpor t ant
t hi ngs, l i k e w hi c h w i l d ani mal s t o av oi d and w het her
nak ed snow b oar di ng i s a b ad i dea.” So how do y ou t r i c k
y our b r ai n i nt o t hi nk i ng t hat y our l i f e depends on
k now i ng Desi gn Pat t er ns?

W ho i s t hi s b ook f or ?

W e k now w hat y ou’r e t hi nk i ng.

A nd w e k now w hat y our b r ai n i s t hi nk i ng.

W e t hi nk of a “Head Fi r st ” r eader as a l ear ner .

Met ac ogni t i on: t hi nk i ng ab out t hi nk i ng

Her e’s w hat W E di d

Her e’s w hat YOU c an do t o b end y our b r ai n i nt o


sub mi ssi on

Read Me

Tec h Rev i ew er s

A c k now l edgment s

1 Welcome to Design Patterns: I ntro to Design


Patterns

Someone has already solv ed y our problems. In t hi s


c hapt er , y ou’l l l ear n w hy (and how ) y ou c an ex pl oi t t he
w i sdom and l essons l ear ned b y ot her dev el oper s w ho’v e
b een dow n t he same desi gn pr ob l em r oad and sur v i v ed t he
t r i p. Bef or e w e’r e done, w e’l l l ook at t he use and b enef i t s
of desi gn pat t er ns, l ook at some k ey ob jec t -or i ent ed (OO)
desi gn pr i nc i pl es, and w al k t hr ough an ex ampl e of how
one pat t er n w or k s. The b est w ay t o use pat t er ns i s t o load
y our brain w i t h t hem and t hen rec ogniz e plac es i n y our
desi gns and ex i st i ng appl i c at i ons w her e y ou c an apply
th em . Inst ead of c ode r euse, w i t h pat t er ns y ou get
experienc e r euse.

It st ar t ed w i t h a si mpl e Si mU Duc k app

But now w e need t he duc k s t o FLY

But somet hi ng w ent hor r i b l y w r ong

Joe t hi nk s ab out i nher i t anc e…

How ab out an i nt er f ac e?

W hat w oul d y ou do i f y ou w er e Joe?

The one c onst ant i n sof t w ar e dev el opment

Zer oi ng i n on t he pr ob l em…

Separ at i ng w hat c hanges f r om w hat st ay s t he


same

Desi gni ng t he Duc k Behav i or s

Impl ement i ng t he Duc k Behav i or s

Int egr at i ng t he Duc k Behav i or

Test i ng t he Duc k c ode

Set t i ng b ehav i or dy nami c al l y

The Bi g Pi c t ur e on enc apsul at ed b ehav i or s

HA S-A c an b e b et t er t han IS-A

Speak i ng of Desi gn Pat t er ns…

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…

The pow er of a shar ed pat t er n v oc ab ul ar y

How do I use Desi gn Pat t er ns?

Tool s f or y our Desi gn Tool b ox

2 Keeping y our Obj ects in the Know: The Observ er


Pattern

Y ou don’t want to miss out when something


interesting happens, do y ou? W e’v e got a pat t er n t hat
k eeps y our ob jec t s in th e k now w hen somet hi ng t hey c are
about happens. It ’s t he Ob ser v er Pat t er n. It i s one of t he
most c ommonl y used desi gn pat t er ns, and i t ’s i nc r edi b l y
usef ul . W e’r e goi ng t o l ook at al l k i nds of i nt er est i ng
aspec t s of Ob ser v er , l i k e i t s one-to-m any relations h ips
and loos e c oupling. A nd, w i t h t hose c onc ept s i n mi nd, how
c an y ou hel p b ut b e t he l i f e of t he Pat t er ns Par t y ?

The W eat her Moni t or i ng appl i c at i on ov er v i ew

Meet t he 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

The Ob ser v er Pat t er n def i ned

The Pow er of Loose Coupl i ng

Desi gni ng t he W eat her St at i on

Impl ement i ng t he W eat her St at i on

Pow er up t he W eat her St at i on

Look i ng f or t he Ob ser v er Pat t er n i n t he W i l d

Codi ng t he l i f e-c hangi ng appl i c at i on

Meanw hi l e, b ac k at W eat her -O-Rama

Test Dr i v e t he new c ode

Tool s f or y our Desi gn Tool b ox

Desi gn Pr i nc i pl e Chal l enge

3 Decorating Obj ects: The Decorator Pattern

Just call this chapter “Design Ey e for the I nheritance


Guy .” W e’l l r e-ex ami ne t he t y pi c al ov er use of
i nher i t anc e and y ou’l l l ear n how t o dec or at e y our c l asses
at r unt i me usi ng a f or m of ob jec t c omposi t i on. W hy ? Onc e
y ou k now t he t ec hni ques of dec or at i ng, y ou’l l b e ab l e t o
gi v e y our (or someone el se’s) ob jec t s new r esponsi b i l i t i es
w ith out m ak ing any c ode c h anges to th e underly ing
c las s es .

W el c ome t o St ar b uzz Cof f ee

The Open-Cl osed Pr i nc i pl e

Meet t he Dec or at or Pat t er n

Const r uc t i ng a dr i nk or der w i t h Dec or at or s

The Dec or at or Pat t er n def i ned

Dec or at i ng our Bev er ages

W r i t i ng t he St ar b uzz c ode

Codi ng b ev er ages

Codi ng c ondi ment s

Ser v i ng some c of f ees

Real -W or l d Dec or at or s: Jav a I/O

Dec or at i ng t he jav a.i o c l asses

W r i t i ng y our ow n Jav a I/O Dec or at or

Test out y our new Jav a I/O Dec or at or

Tool s f or y our Desi gn Tool b ox

4 Baking with OO Goodness: The F actory Pattern

Get ready to bake some loosely coupled OO designs.


Ther e i s mor e t o mak i ng ob jec t s t han just usi ng t he new
oper at or . You’l l l ear n t hat i nst ant i at i on i s an ac t i v i t y
t hat shoul dn’t al w ay s b e done i n pub l i c and c an of t en l ead
t o c oupling problem s . A nd w e don’t w ant th at, do w e? Fi nd
out how Fac t or y Pat t er ns c an hel p sav e y ou f r om
emb ar r assi ng dependenc i es.

Ident i f y i ng t he aspec t s t hat v ar y

Enc apsul at i ng ob jec t c r eat i on

Bui l di ng a si mpl e pi zza f ac t or y

The Si mpl e Fac t or y def i ned

A f r amew or k f or t he pi zza st or e

A l l ow i ng t he sub c l asses t o dec i de

Dec l ar i ng a f ac t or y met hod

It ’s f i nal l y t i me t o meet t he Fac t or y Met hod


Pat t er n
V i ew Cr eat or s and Pr oduc t s i n Par al l el

Fac t or y Met hod Pat t er n def i ned

Look i ng at ob jec t dependenc i es

The Dependenc y Inv er si on Pr i nc i pl e

A ppl y i ng t he Pr i nc i pl e

Fami l i es of i ngr edi ent s…

Bui l di ng t he i ngr edi ent f ac t or i es

Rew or k i ng t he pi zzas…

Rev i si t i ng our pi zza st or es

W hat hav e w e done?

A b st r ac t Fac t or y Pat t er n def i ned

Fac t or y Met hod and A b st r ac t Fac t or y c ompar ed

Tool s f or y our Desi gn Tool b ox

5 One-of-a-Kind Obj ects: The Singleton Pattern

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.

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

The Choc ol at e Fac t or y

Si ngl et on Pat t er n def i ned

Her shey , PA , w e hav e a pr ob l em

Deal i ng w i t h mul t i t hr eadi ng

Can w e i mpr ov e mul t i t hr eadi ng?

Meanw hi l e, b ac k at t he Choc ol at e Fac t or y …

Tool s f or y our Desi gn Tool b ox

6 Encapsulating I nv ocation: The Command Pattern

I n this chapter, we take encapsulation to a whole new


lev el: we’re going to encapsulate method inv ocation.
That ’s r i ght —b y enc apsul at i ng met hod i nv oc at i on, w e
c an c r y st al l i ze pi ec es of c omput at i on so t hat t he ob jec t
i nv ok i ng t he c omput at i on doesn’t need t o w or r y ab out
how t o do t hi ngs, i t just uses our c r y st al l i zed met hod t o
get i t done. W e c an al so do some w i c k edl y smar t t hi ngs
w i t h t hese enc apsul at ed met hod i nv oc at i ons, l i k e sav e
t hem aw ay f or l oggi ng or r euse t hem t o i mpl ement undo
f unc t i onal i t y i n our c ode.

Home A ut omat i on or Bust

Tak i ng a l ook at t he v endor c l asses

A b r i ef i nt r oduc t i on t o t he Command Pat t er n

Fr om t he Di ner t o t he Command Pat t er n

Our f i r st c ommand ob jec t

U si ng t he c ommand ob jec t

A ssi gni ng Commands t o sl ot s

Impl ement i ng t he Remot e Cont r ol

Impl ement i ng t he Commands

Put t i ng t he Remot e Cont r ol t hr ough i t s pac es

Ti me t o w r i t e t hat doc ument at i on…

W hat ar e w e doi ng?

Ti me t o QA t hat U ndo b ut t on!

U si ng st at e t o i mpl ement U ndo

A ddi ng U ndo t o t he Cei l i ng Fan c ommands

Ev er y r emot e needs a Par t y Mode!

U si ng a mac r o c ommand

Mor e uses of t he Command Pat t er n: queui ng


r equest s

Mor e uses of t he Command Pat t er n: l oggi ng


r equest s

Command Pat t er n i n t he Real W or l d

Tool s f or y our Desi gn Tool b ox

7 Being Adaptiv e: The Adapter and F acade Patterns

I n this chapter we’re going to attempt such impossible


feats as putting a square peg in a round hole. Sound
i mpossi b l e? N ot w hen w e hav e Desi gn Pat t er ns.
Rememb er t he Dec or at or Pat t er n? W e wrapped obj ects
t o gi v e t hem new r esponsi b i l i t i es. N ow w e’r e goi ng t o
w r ap some ob jec t s w i t h a di f f er ent pur pose: t o mak e t hei r
i nt er f ac es l ook l i k e somet hi ng t hey ’r e not . W hy w oul d
w e do t hat ? So w e c an adapt a desi gn ex pec t i ng one
i nt er f ac e t o a c l ass t hat i mpl ement s a di f f er ent i nt er f ac e.
That ’s not al l ; w hi l e w e’r e at i t , w e’r e goi ng t o l ook at
anot her pat t er n t hat w r aps ob jec t s t o si mpl i f y t hei r
i nt er f ac e.

A dapt er s al l ar ound us

Ob jec t -or i ent ed adapt er s

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

The A dapt er Pat t er n ex pl ai ned

A dapt er Pat t er n def i ned

Ob jec t and c l ass adapt er s

Real -w or l d adapt er s

A dapt i ng an Enumer at i on t o an It er at or

Home Sw eet Home Theat er

W at c hi ng a mov i e (t he har d w ay )

Li ght s, Camer a, Fac ade!

Const r uc t i ng y our home t heat er f ac ade

Impl ement i ng t he si mpl i f i ed i nt er f ac e

Ti me t o w at c h a mov i e (t he easy w ay )

Fac ade Pat t er n def i ned

The Pr i nc i pl e of Least Know l edge

How N OT t o W i n Fr i ends and Inf l uenc e Ob jec t s

The Fac ade Pat t er n and t he Pr i nc i pl e of Least


Know l edge

Tool s f or y our Desi gn Tool b ox

8 Encapsulating Algorithms: The Template Method


Pattern

We’v e encapsulated obj ect creation, method


inv ocation, complex interfaces, ducks, pizzas…what
could be next? W e’r e goi ng t o get dow n t o enc apsul at i ng
pi ec es of al gor i t hms so t hat sub c l asses c an hook
t hemsel v es r i ght i nt o a c omput at i on any t i me t hey w ant .
W e’r e ev en goi ng t o l ear n ab out a desi gn pr i nc i pl e
i nspi r ed b y Hol l y w ood. Let ’s get st ar t ed…

It ’s t i me f or some mor e c af f ei ne

W hi ppi ng up some c of f ee and t ea c l asses (i n


Jav a)

Let ’s ab st r ac t t hat Cof f ee and Tea

Tak i ng t he desi gn f ur t her …

A b st r ac t i ng pr epar eRec i pe()

W hat hav e w e done?

Meet t he Templ at e Met hod

W hat di d t he Templ at e Met hod get us?

Templ at e Met hod Pat t er n def i ned

Hook ed on Templ at e Met hod…

U si ng t he hook

The Hol l y w ood Pr i nc i pl e and Templ at e Met hod

Templ at e Met hods i n t he W i l d

Sor t i ng w i t h Templ at e Met hod

W e’v e got some duc k s t o sor t …


W hat i s c ompar eTo()?

Compar i ng Duc k s and Duc k s

Let ’s sor t some Duc k s

The mak i ng of t he sor t i ng duc k mac hi ne

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

Tool s f or y our Desi gn Tool b ox

9 Well-Managed Collections: The I terator and


Composite Patterns

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 .

Br eak i ng N ew s: Ob jec t v i l l e Di ner and


Ob jec t v i l l e Panc ak e House Mer ge

Chec k out t he Menu It ems

Impl ement i ng t he spec : our f i r st at t empt

Can w e enc apsul at e t he i t er at i on?

Meet t he It er at or Pat t er n

A ddi ng an It er at or t o Di ner Menu

Rew or k i ng t he Di ner Menu w i t h It er at or

Fi x i ng up t he W ai t r ess c ode

Test i ng our c ode

Rev i ew i ng our c ur r ent desi gn…

Cl eani ng t hi ngs up w i t h jav a.ut i l .It er at or

It er at or Pat t er n def i ned

The It er at or Pat t er n St r uc t ur e

The Si ngl e Responsi b i l i t y Pr i nc i pl e

Meet Jav a’s It er ab l e i nt er f ac e

Jav a’s enhanc ed f or l oop

Tak i ng a l ook at t he Caf é Menu

It er at or s and Col l ec t i ons

Is t he W ai t r ess r eady f or pr i me t i me?

The Composi t e Pat t er n def i ned

Desi gni ng Menus w i t h Composi t e

Impl ement i ng MenuComponent

Impl ement i ng t he MenuIt em

Impl ement i ng t he Composi t e Menu

N ow f or t he t est dr i v e…

Tool s f or y our Desi gn Tool b ox

10 The State of Things: The State Pattern

A little-known fact: the Strategy and State Patterns


were twins separated at birth. You’d t hi nk t hey ’d l i v e
si mi l ar l i v es, b ut t he St r at egy Pat t er n w ent on t o c r eat e a
w i l dl y suc c essf ul b usi ness ar ound i nt er c hangeab l e
al gor i t hms, w hi l e St at e t ook t he per haps mor e nob l e pat h
of hel pi ng ob jec t s t o c ont r ol t hei r b ehav i or b y c hangi ng
t hei r i nt er nal st at e. A s di f f er ent as t hei r pat hs b ec ame,
how ev er , under neat h y ou’l l f i nd al most pr ec i sel y t he
same desi gn. How c an t hat b e? A s y ou’l l see, St r at egy and
St at e hav e v er y di f f er ent i nt ent s. Fi r st , l et ’s di g i n and
see w hat t he St at e Pat t er n i s al l ab out , and t hen w e’l l
r et ur n t o ex pl or e t hei r r el at i onshi p at t he end of t he
c hapt er .

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

You k new i t w as c omi ng…a c hange r equest !

The messy STA TE of t hi ngs…

The new desi gn

Def i ni ng t he St at e i nt er f ac es and c l asses

Rew or k i ng t he Gumb al l Mac hi ne

N ow , l et ’s l ook at t he c ompl et e
Gumb al l Mac hi ne c l ass…

Impl ement i ng mor e st at es

The St at e Pat t er n def i ned

W e st i l l need t o f i ni sh t he Gumb al l 1 i n 1 0 game

Fi ni shi ng t he game

Demo f or t he CEO of Mi ght y Gumb al l , Inc .

Sani t y c hec k …

W e al most f or got !

Tool s f or y our Desi gn Tool b ox

11 Controlling Obj ect Access: The Proxy Pattern

Ev er play good cop, bad cop? You’r e t he good c op and


y ou pr ov i de al l y our ser v i c es i n a ni c e and f r i endl y
manner , b ut y ou don’t w ant ev er y one ask i ng y ou f or
ser v i c es, so y ou hav e t he b ad c op c ont r ol ac c ess t o y ou.
That ’s w hat pr ox i es do: c ont r ol and manage ac c ess. A s
y ou’r e goi ng t o see, t her e ar e l ot s of w ay s i n w hi c h
pr ox i es st and i n f or t he ob jec t s t hey pr ox y . Pr ox i es hav e
b een k now n t o haul ent i r e met hod c al l s ov er t he i nt er net
f or t hei r pr ox i ed ob jec t s; t hey ’v e al so b een k now n t o
pat i ent l y st and i n f or some pr et t y l azy ob jec t s.

Codi ng t he Moni t or

Test i ng t he Moni t or

Remot e met hods 1 01

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

Regi st er i ng w i t h t he RMI r egi st r y …

The Pr ox y Pat t er n def i ned

Get r eady f or t he V i r t ual Pr ox y

Desi gni ng t he A l b um Cov er V i r t ual Pr ox y

W r i t i ng t he Image Pr ox y

U si ng t he Jav a A PI’s Pr ox y t o c r eat e a


pr ot ec t i on pr ox y

Geek y Mat c hmak i ng i n Ob jec t v i l l e

The Per son i mpl ement at i on

Fi v e-mi nut e dr ama: pr ot ec t i ng sub jec t s

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

Tool s f or y our Desi gn Tool b ox

The c ode f or t he A l b um Cov er V i ew er

12 Patterns of Patterns: Compound Patterns

Who would hav e ev er guessed that Patterns could


work together? You’v e al r eady w i t nessed t he
ac r i moni ous Fi r esi de Chat s (and y ou hav en’t ev en seen
t he Pat t er n Deat h Mat c h pages t hat t he edi t or f or c ed us t o
r emov e f r om t he b ook ), so w ho w oul d hav e t hought
pat t er ns c an ac t ual l y get al ong w el l t oget her ? W el l ,
b el i ev e i t or not , some of t he most pow er f ul OO desi gns
use sev er al pat t er ns t oget her . Get r eady t o t ak e y our
pat t er n sk i l l s t o t he nex t l ev el ; i t ’s t i me f or c ompound
pat t er ns.

W or k i ng t oget her

Duc k r euni on

W hat di d w e do?

A b i r d’s duc k ’s-ey e v i ew : t he c l ass di agr am

The Ki ng of Compound Pat t er ns


Meet Model -V i ew -Cont r ol l er

A c l oser l ook …

U nder st andi ng MV C as a set of Pat t er ns

U si ng MV C t o c ont r ol t he b eat …

Bui l di ng t he pi ec es

N ow l et ’s hav e a l ook at t he c onc r et e Beat Model


c l ass

The V i ew

Impl ement i ng t he V i ew

N ow f or t he Cont r ol l er

Put t i ng i t al l t oget her …

Ex pl or i ng St r at egy

A dapt i ng t he Model

A nd now f or a t est r un…

Tool s f or y our Desi gn Tool b ox

13 Patterns in the Real World: Better Liv ing with


patterns

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…

Desi gn Pat t er n def i ned

Look i ng mor e c l osel y at t he Desi gn Pat t er n


def i ni t i on

May t he f or c e b e w i t h y ou

So y ou w anna b e a Desi gn Pat t er ns w r i t er

Or gani zi ng Desi gn Pat t er ns

Thi nk i ng i n Pat t er ns

Your Mi nd on Pat t er ns

Don’t f or get t he pow er of t he shar ed v oc ab ul ar y

Cr ui si n’ Ob jec t v i l l e w i t h t he Gang of Four

Your jour ney has just b egun…

The Pat t er ns Zoo

A nni hi l at i ng ev i l w i t h A nt i -Pat t er ns

Tool s f or y our Desi gn Tool b ox

Leav i ng Ob jec t v i l l e

14 Appendix: Leftov er Patterns

Not ev ery one can be the most popular. A l ot has


c hanged i n t he l ast 25+ y ear s. Si nc e Des ign Patterns :
Elem ents of Reus able Objec t-Oriented S oftw are f i r st c ame
out , dev el oper s hav e appl i ed t hese pat t er ns t housands of
t i mes. The pat t er ns w e summar i ze i n t hi s appendi x ar e
f ul l -f l edged, c ar d-c ar r y i ng, of f i c i al GoF pat t er ns, b ut
ar en’t used as of t en as t he pat t er ns w e’v e ex pl or ed so f ar .
But t hese pat t er ns ar e aw esome i n t hei r ow n r i ght , and i f
y our si t uat i on c al l s f or t hem, y ou shoul d appl y t hem
w i t h y our head hel d hi gh. Our goal i n t hi s appendi x i s t o
gi v e y ou a hi gh-l ev el i dea of w hat t hese pat t er ns ar e al l
ab out .

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?”

Who is this book for?


If y ou c an answ er “y es” t o al l of t hese:

1 . Do y ou k now Jav a (y ou don’t need t o b e a gur u) or anot her


ob jec t -or i ent ed l anguage?

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.

2. Do y ou w ant t o learn, understand, remember, and a p p ly


desi gn pat t er ns, i nc l udi ng t he OO desi gn pr i nc i pl es upon
w hi c h desi gn pat t er ns ar e b ased?

3. Do y ou pr ef er stimulating dinner party conv ersation t o


dr y , dul l , ac ademi c l ec t ur es?

t hi s b ook i s f or y ou.

Who should probably back away from this book?

If y ou c an answ er “y es” t o any one of t hese:

1 . A r e y ou c ompl et el y new t o obj ect-oriented


programming?

2. A r e y ou a k i c k -b ut t ob jec t -or i ent ed desi gner /dev el oper


l ook i ng f or a re fe re nce book?

3. A r e y ou an ar c hi t ec t l ook i ng f or e nte rp ris e desi gn


pat t er ns?

4. A r e y ou afraid to try something different? W oul d y ou


r at her hav e a r oot c anal t han mi x st r i pes w i t h pl ai d? Do
y ou b el i ev e t hat a t ec hni c al b ook c an’t b e ser i ous i f
ob jec t -or i ent ed c onc ept s ar e ant hr opomor phi zed?

t hi s b ook i s not f or y ou.


N O TE
[Note from marketing: this book is for anyone with a credit
card.]

We know what you’re thinking.


“How c an t hi s b e a ser i ous pr ogr ammi ng b ook ?”

“W hat ’s w i t h al l t he gr aphi c s?”

“Can I ac t ual l y l ear n i t t hi s w ay ?”

And we know what your brain is thinking.


Your b r ai n c r av es nov el t y . It ’s al w ay s sear c hi ng, sc anni ng, w aiting
f or somet hi ng unusual . It w as b ui l t t hat w ay , and i t hel ps y ou st ay
al i v e.

Today , y ou’r e l ess l i k el y t o b e a t i ger snac k . But y our b r ai n’s st i l l


l ook i ng. You just nev er k now .

So w hat does y our b r ai n do w i t h al l t he r out i ne, or di nar y , nor mal


t hi ngs y ou enc ount er ? Ev er y t hi ng i t c an t o st op t hem f r om
i nt er f er i ng w i t h t he b r ai n’s real job —r ec or di ng t hi ngs t hat mat t er .
It doesn’t b ot her sav i ng t he b or i ng t hi ngs; t hey nev er mak e i t past
t he “t hi s i s ob v i ousl y not i mpor t ant ” f i l t er .

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 ?

N eur ons f i r e. Emot i ons c r ank up. Ch em ic als s urge.

A nd t hat ’s how y our b r ai n k now s...

This must be important! Don’t forget it!

But i magi ne y ou’r e at home, or i n a l i b r ar y . It ’s a saf e, w ar m, t i ger -


f r ee zone. You’r e st udy i ng. Get t i ng r eady f or an ex am. Or t r y i ng t o
l ear n some t ough t ec hni c al t opi c y our b oss t hi nk s w i l l t ak e a w eek ,
t en day s at t he most .

Just one pr ob l em. Your b r ai n’s t r y i ng t o do y ou a b i g f av or . It ’s


t r y i ng t o mak e sur e t hat t hi s obv ious ly non-i mpor t ant c ont ent
doesn’t c l ut t er up sc ar c e r esour c es. Resour c es t hat ar e b et t er spent
st or i ng t he r eal l y b i g t hi ngs. Li k e t i ger s. Li k e t he danger of f i r e.
Li k e how y ou shoul d nev er agai n snow b oar d i n shor t s.

A nd t her e’s no si mpl e w ay t o t el l y our b r ai n, “Hey b r ai n, t hank y ou


v er y muc h, b ut no mat t er how dul l t hi s b ook i s, and how l i t t l e I’m
r egi st er i ng on t he emot i onal Ri c ht er sc al e r i ght now , I r eal l y do
w ant y ou t o k eep t hi s st uf f ar ound.”
W E T H IN K O F A “ H EAD F IR ST ” R EAD ER AS A
L EAR N ER .
So what does it take to learn something? First, you have to get it, then
make sure you don’t forget it. It’s not about pushing facts into your head.
Based on the latest research in cognitive science, neurobiology, and
educational psychology, learning takes a lot more than text on a page. We
know what turns your brain on.

Some of the Head First learning principles:

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.

Use a conv ersational and personalized style. In studies, students


performed up to 40% better on post-learning tests if the content spoke
directly to the reader, using a first-person, conversational style rather than
taking a formal tone. Tell stories instead of lecturing. Use casual
language. Don’t take yourself too seriously. Which would you pay more
attention to: a stimulating dinner party companion, or a lecture?

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.

Metacognition: thinking about thinking


If y ou r eal l y w ant t o l ear n, and y ou w ant t o l ear n mor e qui c k l y and
mor e deepl y , pay at t ent i on t o how y ou pay at t ent i on. Thi nk ab out
how y ou t hi nk . Lear n how y ou l ear n.

Most of us di d not t ak e c our ses on met ac ogni t i on or l ear ni ng t heor y


w hen w e w er e gr ow i ng up. W e w er e expec ted t o l ear n, b ut r ar el y
taugh t t o l ear n.

But w e assume t hat i f y ou’r e hol di ng t hi s b ook , y ou r eal l y w ant t o


l ear n desi gn pat t er ns. A nd y ou pr ob ab l y don’t w ant t o spend a l ot of
t i me. A nd y ou w ant t o rem em ber w hat y ou r ead, and b e ab l e t o
appl y i t . A nd f or t hat , y ou’v e got t o unders tand i t . To get t he most
f r om t hi s b ook , or any b ook or l ear ni ng ex per i enc e, t ak e
r esponsi b i l i t y f or y our b r ai n. Your b r ai n on th is c ont ent .

The t r i c k i s t o get y our b r ai n t o see t he new mat er i al y ou’r e


l ear ni ng as Real l y Impor t ant . Cr uc i al t o y our w el l -b ei ng. A s
i mpor t ant as a t i ger . Ot her w i se, y ou’r e i n f or a c onst ant b at t l e,
w i t h y our b r ai n doi ng i t s b est t o k eep t he new c ont ent f r om
st i c k i ng.

So how DO y ou get y our brain to think Design Patterns are as


important as a tiger?

Ther e’s t he sl ow , t edi ous w ay , or t he f ast er , mor e ef f ec t i v e w ay . The


sl ow w ay i s ab out sheer r epet i t i on. You ob v i ousl y k now t hat y ou
are ab l e t o l ear n and r ememb er ev en t he dul l est of t opi c s, i f y ou
k eep poundi ng on t he same t hi ng. W i t h enough r epet i t i on, y our
b r ai n say s, “Thi s doesn’t feel i mpor t ant t o hi m, b ut he k eeps l ook i ng
at t he same t hi ng ov er and ov er and ov er, so I suppose i t must b e.”

The f ast er w ay i s t o do a ny th ing th a t incre a s e s b ra in


a ctiv ity , espec i al l y di f f er ent ty pes of b r ai n ac t i v i t y . The t hi ngs
on t he pr ev i ous page ar e a b i g par t of t he sol ut i on, and t hey ’r e al l
t hi ngs t hat hav e b een pr ov en t o hel p y our b r ai n w or k i n y our
f av or . For ex ampl e, st udi es show t hat put t i ng w or ds w ith in t he
pi c t ur es t hey desc r i b e (as opposed t o somew her e el se i n t he page,
l i k e a c apt i on or i n t he b ody t ex t ) c auses y our b r ai n t o t r y t o mak es
sense of how t he w or ds and pi c t ur e r el at e, and t hi s c auses mor e
neur ons t o f i r e. Mor e neur ons f i r i ng = mor e c hanc es f or y our b r ai n
t o get t hat t hi s i s somet hi ng w or t h pay i ng at t ent i on t o, and
possi b l y r ec or di ng.

A c onv er sat i onal st y l e hel ps b ec ause peopl e t end t o pay mor e


at t ent i on w hen t hey per c ei v e t hat t hey ’r e i n a c onv er sat i on, si nc e
t hey ’r e ex pec t ed t o f ol l ow al ong and hol d up t hei r end. The amazi ng
t hi ng i s, y our b r ai n doesn’t nec essar i l y c are t hat t he
“c onv er sat i on” i s b et w een y ou and a b ook ! On t he ot her hand, i f t he
w r i t i ng st y l e i s f or mal and dr y , y our b r ai n per c ei v es i t t he same
w ay y ou ex per i enc e b ei ng l ec t ur ed t o w hi l e si t t i ng i n a r oomf ul of
passi v e at t endees. N o need t o st ay aw ak e.

But pi c t ur es and c onv er sat i onal st y l e ar e just t he b egi nni ng.

Here’s what WE did:


W e used p icture s , b ec ause y our b r ai n i s t uned f or v i sual s, not
t ex t . A s f ar as y our b r ai n’s c onc er ned, a pi c t ur e r eal l y i s w or t h
1 ,024 w or ds. A nd w hen t ex t and pi c t ur es w or k t oget her , w e
emb edded t he t ex t i n t he pi c t ur es b ec ause y our b r ai n w or k s mor e
ef f ec t i v el y w hen t he t ex t i s w i t hi n t he t hi ng i t r ef er s t o, as
opposed t o i n a c apt i on or b ur i ed somew her e el se.

W e used re d und a ncy , say i ng t he same t hi ng i n different w ay s and


w i t h di f f er ent medi a t y pes, and m ultiple s ens es , t o i nc r ease t he
c hanc e t hat t he c ont ent get s c oded i nt o mor e t han one ar ea of y our
b r ai n.

W e used c onc ept s and pi c t ur es i n une xp e cte d w ay s b ec ause y our


b r ai n i s t uned f or nov el t y , and w e used pi c t ur es and i deas w i t h at
l east s om e e m o tio na l c ontent, b ec ause y our b r ai n i s t uned t o pay
at t ent i on t o t he b i oc hemi st r y of emot i ons. That w hi c h c auses y ou
t o feel somet hi ng i s mor e l i k el y t o b e r ememb er ed, ev en i f t hat
f eel i ng i s not hi ng mor e t han a l i t t l e h um o r, s urp ris e , or
inte re s t.

W e used a per sonal i zed, co nv e rs a tio na l s ty le , b ec ause y our


b r ai n i s t uned t o pay mor e at t ent i on w hen i t b el i ev es y ou’r e i n a
c onv er sat i on t han i f i t t hi nk s y ou’r e passi v el y l i st eni ng t o a
pr esent at i on. Your b r ai n does t hi s ev en w hen y ou’r e reading.

W e i nc l uded mor e t han 90 a ctiv itie s , b ec ause y our b r ai n i s t uned


t o l ear n and r ememb er mor e w hen y ou d o t hi ngs t han w hen y ou
r ead ab out t hi ngs. A nd w e made t he ex er c i ses c hal l engi ng-y et -do-
ab l e, b ec ause t hat ’s w hat most people pr ef er .

W e used m ultip le le a rning s ty le s , b ec ause y ou mi ght pr ef er


st ep-b y -st ep pr oc edur es, w hi l e someone el se w ant s t o under st and
t he b i g pi c t ur e f i r st , w hi l e someone el se just w ant s t o see a c ode
ex ampl e. But r egar dl ess of y our ow n l ear ni ng pr ef er enc e, ev ery one
b enef i t s f r om seei ng t he same c ont ent r epr esent ed i n mul t i pl e
w ay s.
W e i nc l uded c ont ent f or b o th s id e s o f y o ur b ra in, b ec ause t he
mor e of y our b r ai n y ou engage, t he mor e l i k el y y ou ar e t o l ear n and
r ememb er , and t he l onger y ou c an st ay f oc used. Si nc e w or k i ng one
si de of t he b r ai n of t en means gi v i ng t he ot her si de a c hanc e t o r est ,
y ou c an b e mor e pr oduc t i v e at l ear ni ng f or a l onger per i od of t i me.

A nd w e i nc l uded s to rie s and ex er c i ses t hat pr esent m o re th a n


o ne p o int o f v ie w , b ec ause y our b r ai n i s t uned t o l ear n mor e
deepl y w hen i t ’s f or c ed t o mak e ev al uat i ons and judgment s.

W e i nc l uded ch a lle ng e s , b ot h w i t h ex er c i ses and b y ask i ng


q ue s tio ns t hat don’t al w ay s hav e a st r ai ght answ er , b ec ause y our
b r ai n i s t uned t o l ear n and r ememb er w hen i t has t o w ork at
somet hi ng. Thi nk ab out i t —y ou c an’t get y our body i n shape just b y
w atc h ing peopl e at t he gy m. But w e di d our b est t o mak e sur e t hat
w hen y ou’r e w or k i ng har d, i t ’s on t he righ t t hi ngs. That y o u’re no t
s p e nd ing o ne e xtra d e nd rite pr oc essi ng a har d-t o-under st and
ex ampl e, or par si ng di f f i c ul t , jar gon-l aden, or ov er l y t er se t ex t .

W e used p e o p le . In st or i es, ex ampl es, pi c t ur es, et c ., b ec ause, w el l ,


b ec ause y ou’re a per son. A nd y our b r ai n pay s mor e at t ent i on t o
people t han i t does t o th ings .

W e used an 80/20 appr oac h. W e assume t hat i f y ou’r e goi ng f or a


PhD i n sof t w ar e desi gn, t hi s w on’t b e y our onl y b ook . So w e don’t
t al k ab out ev ery th ing. Just t he st uf f y ou’l l ac t ual l y need.

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


submission
So, w e di d our par t . The r est i s up t o y ou. These t i ps ar e a st ar t i ng
poi nt ; l i st en t o y our b r ai n and f i gur e out w hat w or k s f or y ou and
w hat doesn’t . Tr y new t hi ngs.

N O TE
Cut this out and stick it on your refrigerator.

1 . Slow down. The more y ou understand, the less y ou


hav e to memorize.

Don’t just read. St op and t hi nk . W hen t he b ook ask s y ou a


quest i on, don’t just sk i p t o t he answ er . Imagi ne t hat
someone r eal l y i s ask i ng t he quest i on. The mor e deepl y
y ou f or c e y our b r ai n t o t hi nk , t he b et t er c hanc e y ou hav e
of l ear ni ng and r ememb er i ng.

2. Do the exercises. Write y our own notes.

W e put t hem i n, b ut i f w e di d t hem f or y ou, t hat w oul d b e


l i k e hav i ng someone el se do y our w or k out s f or y ou. A nd
don’t just look at t he ex er c i ses. Use a pencil. Ther e’s
pl ent y of ev i denc e t hat phy si c al ac t i v i t y w h ile l ear ni ng
c an i nc r ease t he l ear ni ng.

3. Read the “There Are No Dumb Questions”

That means al l of t hem. They ’r e not opt i onal si deb ar s—


th e y ’re p a rt o f th e co re co nte nt! Don’t sk i p t hem.

4. Make this the last thing y ou read before bed. Or at


least the last ch a lle ng ing thing.

Par t of t he l ear ni ng (espec i al l y t he t r ansf er t o l ong-t er m


memor y ) happens after y ou put t he b ook dow n. Your b r ai n
needs t i me on i t s ow n, t o do mor e pr oc essi ng. If y ou put i n
somet hi ng new dur i ng t hat pr oc essi ng t i me, some of w hat
y ou just l ear ned w i l l b e l ost .

5. Drink water. Lots of it.

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.

6. Talk about it. Out loud.

Speak i ng ac t i v at es a di f f er ent par t of t he b r ai n. If y ou’r e


t r y i ng t o under st and somet hi ng, or i nc r ease y our c hanc e
of r ememb er i ng i t l at er , say i t out l oud. Bet t er st i l l , t r y t o
ex pl ai n i t out l oud t o someone el se. You’l l l ear n mor e
qui c k l y , and y ou mi ght unc ov er i deas y ou hadn’t k now n
w er e t her e w hen y ou w er e r eadi ng ab out i t .

7 . Listen to y our brain.

Pay at t ent i on t o w het her y our b r ai n i s get t i ng


ov er l oaded. If y ou f i nd y our sel f st ar t i ng t o sk i m t he
sur f ac e or f or get w hat y ou just r ead, i t ’s t i me f or a b r eak .
Onc e y ou go past a c er t ai n poi nt , y ou w on’t l ear n f ast er
b y t r y i ng t o shov e mor e i n, and y ou mi ght ev en hur t t he
pr oc ess.

8. Fe e l something!

Your b r ai n needs t o k now t hat t hi s m atters . Get i nv ol v ed


w i t h t he st or i es. Mak e up y our ow n c apt i ons f or t he
phot os. Gr oani ng ov er a b ad jok e i s s till b et t er t han
f eel i ng not hi ng at al l .

9. De s ig n something!

A ppl y t hi s t o somet hi ng new y ou’r e desi gni ng, or r ef ac t or


an ol der pr ojec t . Just do s om eth ing t o get some
ex per i enc e b ey ond t he ex er c i ses and ac t i v i t i es i n t hi s
b ook . A l l y ou need i s a penc i l and a pr ob l em t o sol v e…a
pr ob l em t hat mi ght b enef i t f r om one or mor e desi gn
pat t er ns.

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.

We use simple UML-like diagrams.


A l t hough t her e’s a good c hanc e y ou’v e r un ac r oss U ML, i t ’s not
c ov er ed i n t he b ook , and i t ’s not a pr er equi si t e f or t he b ook . If
y ou’v e nev er seen U ML b ef or e, don’t w or r y , w e’l l gi v e y ou a f ew
poi nt er s al ong t he w ay . So i n ot her w or ds, y ou w on’t hav e t o w or r y
ab out Desi gn Pat t er ns and U ML at t he same t i me. Our di agr ams ar e
“U ML-lik e”—w hi l e w e t r y t o b e t r ue t o U ML t her e ar e t i mes w e
b end t he r ul es a b i t , usual l y f or our ow n sel f i sh ar t i st i c r easons.
We don’t cover every single Design Pattern ever created.

Ther e ar e a lot of Desi gn Pat t er ns: t he or i gi nal f oundat i onal


pat t er ns (k now n as t he GoF pat t er ns), ent er pr i se Jav a pat t er ns,
ar c hi t ec t ur al pat t er ns, game desi gn pat t er ns, and a l ot mor e. But
our goal w as t o mak e sur e t he b ook w ei ghed l ess t han t he per son
r eadi ng i t , so w e don’t c ov er t hem al l her e. Our f oc us i s on t he c or e
pat t er ns t hat m atter f r om t he or i gi nal GoF ob jec t -or i ent ed
pat t er ns, and mak i ng sur e t hat y ou r eal l y , t r ul y , deepl y under st and
how and w hen t o use t hem. You w i l l f i nd a b r i ef l ook at some of t he
ot her pat t er ns (t he ones y ou’r e f ar l ess l i k el y t o use) i n t he
appendi x . In any c ase, onc e y ou’r e done w i t h Head Firs t Des ign
Patterns , y ou’l l b e ab l e t o pi c k up any pat t er ns c at al og and get up t o
speed qui c k l y .

The activities are NOT optional.

The ex er c i ses and ac t i v i t i es ar e not add-ons; t hey ’r e par t of t he c or e


c ont ent of t he b ook . Some of t hem ar e t o hel p w i t h memor y , some
f or under st andi ng, and some t o hel p y ou appl y w hat y ou’v e l ear ned.
Do n’t s k ip th e e xe rcis e s . The c r ossw or d puzzl es ar e t he onl y
t hi ngs y ou don’t h av e t o do, b ut t hey ’r e good f or gi v i ng y our b r ai n a
c hanc e t o t hi nk ab out t he w or ds f r om a di f f er ent c ont ex t .

We use the word “composition” in the general OO sense, which is


more flexible than the strict UML use of “composition.”

W hen w e say “one ob jec t i s c omposed w i t h anot her ob jec t ” w e mean


t hat t hey ar e r el at ed b y a HA S-A r el at i onshi p. Our use r ef l ec t s t he
t r adi t i onal use of t he t er m and i s t he one used i n t he GoF t ex t
(y ou’l l l ear n w hat t hat i s l at er ). Mor e r ec ent l y , U ML has r ef i ned
t hi s t er m i nt o sev er al t y pes of c omposi t i on. If y ou ar e an U ML
ex per t , y ou’l l st i l l b e ab l e t o r ead t he b ook and y ou shoul d b e ab l e
t o easi l y map t he use of c omposi t i on t o mor e r ef i ned t er ms as y ou
r ead.

The redundancy is intentional and important.

One di st i nc t di f f er enc e i n a Head Fi r st b ook i s t hat w e w ant y ou t o


really get i t . A nd w e w ant y ou t o f i ni sh t he b ook r ememb er i ng w hat
y ou’v e l ear ned. Most r ef er enc e b ook s don’t hav e r et ent i on and
r ec al l as a goal , b ut t hi s b ook i s ab out learning, so y ou’l l see some of
t he same c onc ept s c ome up mor e t han onc e.

The code examples are as lean as possible.

Our r eader s t el l us t hat i t ’s f r ust r at i ng t o w ade t hr ough 200 l i nes


of c ode l ook i ng f or t he t w o l i nes t hey need t o under st and. Most
ex ampl es i n t hi s b ook ar e show n w i t hi n t he smal l est possi b l e
c ont ex t , so t hat t he par t y ou’r e t r y i ng t o l ear n i s c l ear and si mpl e.
Don’t ex pec t al l of t he c ode t o b e r ob ust , or ev en c ompl et e—t he
ex ampl es ar e w r i t t en spec i f i c al l y f or l ear ni ng, and ar en’t al w ay s
f ul l y f unc t i onal .

In some c ases, w e hav en’t i nc l uded al l of t he i mpor t st at ement s


needed, b ut w e assume t hat i f y ou’r e a Jav a pr ogr ammer , y ou k now
t hat ArrayList i s i n jav a.ut i l , f or ex ampl e. If t he i mpor t s w er e not
par t of t he nor mal c or e JSE A PI, w e ment i on i t . W e’v e al so pl ac ed
al l t he sour c e c ode on t he w eb so y ou c an dow nl oad i t . You’l l f i nd i t
at http://wickedlysmart.com/head-first-design-patterns.

A l so, f or t he sak e of f oc usi ng on t he l ear ni ng si de of t he c ode, w e di d


not put our c l asses i nt o pac k ages (i n ot her w or ds, t hey ’r e al l i n t he
Jav a def aul t pac k age). W e don’t r ec ommend t hi s i n t he r eal w or l d,
and w hen y ou dow nl oad t he c ode ex ampl es f r om t hi s b ook , y ou’l l
f i nd t hat al l c l asses are i n pac k ages.

The Brain Power exercises don’t have answers.

For some of t hem, t her e i s no r i ght answ er , and f or ot her s, par t of


t he l ear ni ng ex per i enc e of t he Br ai n Pow er ac t i v i t i es i s f or y ou t o
dec i de i f and w hen y our answ er s ar e r i ght . In some of t he Br ai n
Pow er ex er c i ses, y ou w i l l f i nd hi nt s t o poi nt y ou i n t he r i ght
di r ec t i on.

Tech Reviewers
Tech Reviewers, 2nd Edition

Acknowledgments

From the first edition

At O’Re illy :

Our b i ggest t hank s t o Mike Loukides at O’Rei l l y , f or st ar t i ng i t al l


and hel pi ng t o shape t he Head Fi r st c onc ept i nt o a ser i es. A nd a b i g
t hank s t o t he dr i v i ng f or c e b ehi nd Head Fi r st , Tim O’Reilly . Thank s
t o t he c l ev er Head Fi r st “ser i es mom” Ky le Hart, “In Desi gn Ki ng”
Ron Bilodeau, r oc k -and-r ol l st ar Ellie Volkhausen f or her
i nspi r ed c ov er desi gn, Melanie Y arbrough f or shepher di ng
pr oduc t i on, Colleen Gorman and Rachel Monaghan f or t hei r
har dc or e c opy edi t s, and Bob Pfahler f or a muc h i mpr ov ed i ndex .
Fi nal l y , t hank s t o Mike Hendrickson and Meghan Blanchette f or
c hampi oni ng t hi s b ook and b ui l di ng t he t eam.

Our intre p id re v ie w e rs :

W e ar e ex t r emel y gr at ef ul f or our t ec hni c al r ev i ew di r ec t or


Johannes deJong. You ar e our her o, Johannes. A nd w e deepl y
appr ec i at e t he c ont r i b ut i ons of t he c o-manager of t he Jav aranch
r ev i ew t eam, t he l at e Philippe Maquet. You hav e si ngl e-handedl y
b r i ght ened t he l i v es of t housands of dev el oper s, and t he i mpac t
y ou’v e had on t hei r (and our ) l i v es i s f or ev er . Jef Cumps i s sc ar i l y
good at f i ndi ng pr ob l ems i n our dr af t c hapt er s, and onc e agai n made
a huge di f f er enc e f or t he b ook . Thank s Jef ! Valentin Cretazz (A OP
guy ), w ho has b een w i t h us f r om t he v er y f i r st Head Fi r st b ook ,
pr ov ed (as al w ay s) just how muc h w e r eal l y need hi s t ec hni c al
ex per t i se and i nsi ght . You r oc k V al ent i n (b ut l ose t he t i e).

Tw o new c omer s t o t he HF r ev i ew t eam, Barney Marispini and I ke


Van Atta, di d a k i c k -b ut t job on t he b ook —y ou guy s gav e us some
really c r uc i al f eedb ac k . Thank s f or joi ni ng t he t eam.

W e al so got some ex c el l ent t ec hni c al hel p f r om Jav ar anc h


moder at or s/gur us Mark Spritzler, Jason Menard, Dirk
Schreckmann, Thomas Paul, and Margarita I saev a. A nd as
al w ay s, t hank s espec i al l y t o t he jav ar anc h.c om (http://javaranch.com)
Tr ai l Boss, Paul Wheaton.

Thank s t o t he f i nal i st s of t he Jav ar anc h “Pi c k t he Head Firs t


Des ign Patterns Cov er ” c ont est . The w i nner , Si Br ew st er , sub mi t t ed
t he w i nni ng essay t hat per suaded us t o pi c k t he w oman y ou see on
our c ov er . Ot her f i nal i st s i nc l ude A ndr ew Esse, Gi an Fr anc o
Casul a, Hel en Cr osb i e, Pho Tek , Hel en Thomas, Sat eesh Kommi neni ,
and Jef f Fi sher .

For t he 201 4 updat e t o t he b ook , w e ar e so gr at ef ul t o t he f ol l ow i ng


t ec hni c al r ev i ew er s: Geor ge Hof f er , Ted Hi l l , Todd Bar t oszk i ew i c z,
Sy l v ai n Teni er , Sc ot t Dav i dson, Kev i n Ry an, Ri c h W ar d, Mar k
Fr anc i s Jaeger , Mar k Masse, Gl enn Ray , Bay ar d Fet l er , Paul
Hi ggi ns, Mat t Car pent er , Jul i a W i l l i ams, Mat t Mc Cul l ough, and
Mar y A nn Bel ar mi no.

Acknowledgments

From the second edition

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 !

Our 2nd e d itio n re v ie w e rs :

W e’r e gr at ef ul t o our 2nd edi t i on t ec hni c al r ev i ew er s f or pi c k i ng


up t he t ask 1 5 y ear s l at er . Dav id Powers i s our go-t o r ev i ew er (he’s
our s, don’t ev en t hi nk ab out ask i ng hi m t o r ev i ew y our b ook )
b ec ause he doesn’t mi ss a t hi ng. George Heineman w ent ab ov e and
b ey ond w i t h hi s det ai l ed c omment s, suggest i ons, and f eedb ac k , and
he r ec ei v ed t hi s edi t i on’s t ec hni c al MV P aw ar d. Trisha Gee and
Julian Setiawan pr ov i ded t he i nv al uab l e Jav a sav v y w e needed t o
hel p us av oi d t hose emb ar r assi ng and c r i nge-w or t hy Jav a mi st ak es.
Thank y ou al l !

Very Special Thanks

A v er y spec i al t hank s t o Erich Gamma, w ho w ent f ar b ey ond t he


c al l of dut y i n r ev i ew i ng t hi s b ook (he ev en t ook a dr af t w i t h hi m
on v ac at i on). Er i c h, y our i nt er est i n t hi s b ook i nspi r ed us, and y our
t hor ough t ec hni c al r ev i ew i mpr ov ed i t i mmeasur ab l y . Thank s as
w el l t o t he ent i r e Gang of F our f or t hei r suppor t and i nt er est , and
f or mak i ng a spec i al appear anc e i n Ob jec t v i l l e. W e ar e al so
i ndeb t ed t o Ward Cunningham and t he pat t er ns c ommuni t y w ho
c r eat ed t he Por t l and Pat t er n Reposi t or y —an i ndi spensab l e
r esour c e f or us i n w r i t i ng t hi s b ook .

A b i g t hank y ou t o Mike Loukides, Mike Hendrickson, and


Meghan Blanchette. Mi k e L. w as w i t h us ev er y st ep of t he w ay .
Mi k e, y our i nsi ght f ul f eedb ac k hel ped shape t he b ook , and y our
enc our agement k ept us mov i ng ahead. Mi k e H., t hank s f or y our
per si st enc e ov er f i v e y ear s i n t r y i ng t o get us t o w r i t e a pat t er ns
b ook ; w e f i nal l y di d i t and w e’r e gl ad w e w ai t ed f or Head Fi r st .

It t ak es a v i l l age t o w r i t e a t ec hni c al b ook : Bill Pugh and Ken


Arnold gav e us ex per t adv i c e on Si ngl et on. Joshua Marinacci
pr ov i ded r oc k i n’ Sw i ng t i ps and adv i c e. John Brewer’s “W hy a
Duc k ?” paper i nspi r ed Si mU Duc k (and w e’r e gl ad he l i k es duc k s
t oo). Dan F riedman i nspi r ed t he Li t t l e Si ngl et on ex ampl e. Daniel
Steinberg ac t ed as our “t ec hni c al l i ason” and our emot i onal
suppor t net w or k . Thank s t o A ppl e’s James Dempsey f or al l ow i ng
us t o use hi s MV C song. A nd t hank y ou t o Richard Warburton, w ho
made sur e our Jav a 8 c ode updat es w er e up t o snuf f f or t hi s updat ed
edi t i on of t he b ook .

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 .

W r i t i ng a Head Fi r st b ook i s a w i l d r i de w i t h t w o amazi ng t our


gui des: Kathy Sierra and Bert Bates. W i t h Kat hy and Ber t y ou
t hr ow out al l b ook w r i t i ng c onv ent i on and ent er a w or l d f ul l of
st or y t el l i ng, l ear ni ng t heor y , c ogni t i v e sc i enc e, and pop c ul t ur e,
w her e t he r eader al w ay s r ul es.
Chapter 1. Welcome to Design
Patterns: Intro to Design Patterns

Someone has already solv ed y our problems. In t hi s c hapt er ,


y ou’l l l ear n w hy (and how ) y ou c an ex pl oi t t he w i sdom and l essons
l ear ned b y ot her dev el oper s w ho’v e b een dow n t he same desi gn
pr ob l em r oad and sur v i v ed t he t r i p. Bef or e w e’r e done, w e’l l l ook at
t he use and b enef i t s of desi gn pat t er ns, l ook at some k ey ob jec t -
or i ent ed (OO) desi gn pr i nc i pl es, and w al k t hr ough an ex ampl e of
how one pat t er n w or k s. The b est w ay t o use pat t er ns i s t o load y our
brain w i t h t hem and t hen rec ogniz e plac es i n y our desi gns and
ex i st i ng appl i c at i ons w her e y ou c an apply th em . Inst ead of c ode
r euse, w i t h pat t er ns y ou get experienc e r euse.

It started with a simple SimUDuck app


Joe w or k s f or a c ompany t hat mak es a hi ghl y suc c essf ul duc k pond
si mul at i on game, S im UDuc k . The game c an show a l ar ge v ar i et y of
duc k spec i es sw i mmi ng and mak i ng quac k i ng sounds. The i ni t i al
desi gner s of t he sy st em used st andar d OO t ec hni ques and c r eat ed
one Duc k super c l ass f r om w hi c h al l ot her duc k t y pes i nher i t .

In t he l ast y ear , t he c ompany has b een under i nc r easi ng pr essur e


f r om c ompet i t or s. A f t er a w eek -l ong of f -si t e b r ai nst or mi ng sessi on
ov er gol f , t he c ompany ex ec ut i v es t hi nk i t ’s t i me f or a b i g
i nnov at i on. They need somet hi ng really i mpr essi v e t o show at t he
upc omi ng shar ehol der s meet i ng i n Maui next w eek .

But now we need the ducks to FLY


The ex ec ut i v es dec i ded t hat f l y i ng duc k s i s just w hat t he si mul at or
needs t o b l ow aw ay t he c ompet i t or s. A nd of c our se Joe’s manager
t ol d t hem i t ’l l b e no pr ob l em f or Joe t o just w hi p somet hi ng up i n a
w eek . “A f t er al l ,” sai d Joe’s b oss, “he’s an OO pr ogr ammer …h ow
h ard c an it be?”
But something went horribly wrong...

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 .

Joe thinks about inheritance...

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.)

A. Code is duplicated across subclasses.

B. Runtime behavior changes are difficult.

C. We can’t make ducks dance.

D. It’s hard to gain knowledge of all duck behaviors.

E. Ducks can’t fly and quack at the same time.

F. Changes can unintentionally affect other ducks.

How about an interface?


Joe r eal i zed t hat i nher i t anc e pr ob ab l y w asn’t t he answ er , b ec ause
he just got a memo t hat say s t hat t he ex ec ut i v es now w ant t o updat e
t he pr oduc t ev er y si x mont hs (i n w ay s t hey hav en’t y et dec i ded on).
Joe k now s t he spec w i l l k eep c hangi ng and he’l l b e f or c ed t o l ook at
and possi b l y ov er r i de f l y () and quac k () f or ev er y new Duc k
sub c l ass t hat ’s ev er added t o t he pr ogr am... forev er.

So, he needs a c l eaner w ay t o hav e onl y s om e (b ut not all) of t he


duc k t y pes f l y or quac k .

What would you do if you were Joe?


W e k now t hat not all of t he sub c l asses shoul d hav e f l y i ng or
quac k i ng b ehav i or , so i nher i t anc e i sn’t t he r i ght answ er . But w hi l e
hav i ng t he sub c l asses i mpl ement Fl y ab l e and/or Quac k ab l e sol v es
part of t he pr ob l em (no i nappr opr i at el y f l y i ng r ub b er duc k s), i t
c ompl et el y dest r oy s c ode r euse f or t hose b ehav i or s, so i t just
c r eat es a different mai nt enanc e ni ght mar e. A nd of c our se t her e
mi ght b e mor e t han one k i nd of f l y i ng b ehav i or ev en among t he
duc k s t hat do f l y ...
A t t hi s poi nt y ou mi ght b e w ai t i ng f or a Desi gn Pat t er n t o c ome
r i di ng i n on a w hi t e hor se and sav e t he day . But w hat f un w oul d
t hat b e? N o, w e’r e goi ng t o f i gur e out a sol ut i on t he ol d-f ashi oned
w ay —by apply ing good OO s oftw are des ign princ iples .

The one constant in software development


Okay , what’s the one thing y ou can alway s count on in software
dev elopment?

N o mat t er w her e y ou w or k , w hat y ou’r e b ui l di ng, or w hat l anguage


y ou ar e pr ogr ammi ng i n, w hat ’s t he one t r ue c onst ant t hat w i l l b e
w i t h y ou al w ay s?

N o mat t er how w el l y ou desi gn an appl i c at i on, ov er t i me an


appl i c at i on must gr ow and c hange or i t w i l l die.
SH AR PEN YO U R PEN C IL
Lots of things can drive change. List some reasons you’ve had to change
code in your applications (we put in a couple of our own to get you started).
Check your answers with the solution at the end of the chapter before you
go on.

My customers or users decide they want something else, or they want new
functionality.

My company decided it is going with another database vendor and it is also


purchasing its data from another supplier that uses a different data format.
Argh!

____________________________________________________________
_________

____________________________________________________________
_________

____________________________________________________________
_________

____________________________________________________________
_________

____________________________________________________________
_________

Zeroing in on the problem...


So w e k now usi ng i nher i t anc e hasn’t w or k ed out v er y w el l , si nc e
t he duc k b ehav i or k eeps c hangi ng ac r oss t he sub c l asses, and i t ’s not
appr opr i at e f or all sub c l asses t o hav e t hose b ehav i or s. The Fl y ab l e
and Quac k ab l e i nt er f ac e sounded pr omi si ng at f i r st —onl y duc k s
t hat r eal l y do f l y w i l l b e Fl y ab l e, et c .—ex c ept Jav a i nt er f ac es
t y pi c al l y hav e no i mpl ement at i on c ode, so no c ode r euse. In ei t her
c ase, w henev er y ou need t o modi f y a b ehav i or , y ou’r e of t en f or c ed
t o t r ac k dow n and c hange i t i n al l t he di f f er ent sub c l asses w her e
t hat b ehav i or i s def i ned, pr ob ab l y i nt r oduc i ng new b ugs al ong t he
w ay !

Luc k i l y , t her e’s a desi gn pr i nc i pl e f or just t hi s si t uat i on.

In ot her w or ds, i f y ou’v e got some aspec t of y our c ode t hat i s


c hangi ng, say w i t h ev er y new r equi r ement , t hen y ou k now y ou’v e
got a b ehav i or t hat needs t o b e pul l ed out and separ at ed f r om al l
t he st uf f t hat doesn’t c hange.

Her e’s anot her w ay t o t hi nk ab out t hi s pr i nc i pl e: ta k e th e p a rts


th a t v a ry a nd e nca p s ula te th e m , s o th a t la te r y o u ca n
a lte r o r e xte nd th e p a rts th a t v a ry w ith o ut a ffe cting
th o s e th a t d o n’t.

A s si mpl e as t hi s c onc ept i s, i t f or ms t he b asi s f or al most ev er y


desi gn pat t er n. A l l pat t er ns pr ov i de a w ay t o l et s om e part of a
s y s tem v ary independently of all oth er parts .

Ok ay , t i me t o pul l t he duc k b ehav i or out of t he Duc k c l asses!

Ta k e w h a t v a rie s a nd “e nca p s ula te ” it s o it w o n’t


a ffe ct th e re s t o f y o ur co d e .

Th e re s ult? Fe w e r uninte nd e d co ns e q ue nce s fro m


co d e ch a ng e s a nd m o re f le xib ility in y o ur s y s te m s !

Separating what changes from what stays the same


W her e do w e st ar t ? A s f ar as w e c an t el l , ot her t han t he pr ob l ems
w i t h f l y () and quac k (), t he Duc k c l ass i s w or k i ng w el l and t her e ar e
no ot her par t s of i t t hat appear t o v ar y or c hange f r equent l y . So,
ot her t han a f ew sl i ght c hanges, w e’r e goi ng t o pr et t y muc h l eav e
t he Duc k c l ass al one.

N ow , t o separ at e t he “par t s t hat c hange f r om t hose t hat st ay t he


same,” w e ar e goi ng t o c r eat e t w o s ets of c l asses (t ot al l y apar t f r om
Duc k ), one f or fly and one f or q uac k . Eac h set of c l asses w i l l hol d al l
t he i mpl ement at i ons of t he r espec t i v e b ehav i or . For i nst anc e, w e
mi ght hav e one c l ass t hat i mpl ement s q uac k ing, anoth er t hat
i mpl ement s s q ueak ing, and anoth er t hat i mpl ement s s ilenc e.

We know that fly () and quack() are the parts of the


Duck class that v ary across ducks.

To separ at e t hese b ehav i or s f r om t he Duc k c l ass, w e’l l


pul l b ot h met hods out of the Duck class and create a
new set of classes to represent each behav ior.
Designing the Duck Behaviors
So how are we going to design the set of classes that implement
the fly and quack behav iors?

W e’d l i k e t o k eep t hi ngs f l ex i b l e; af t er al l , i t w as t he i nf l ex i b i l i t y


i n t he duc k b ehav i or s t hat got us i nt o t r oub l e i n t he f i r st pl ac e.
A nd w e k now t hat w e w ant t o as s ign b ehav i or s t o t he i nst anc es of
Duc k . For ex ampl e, w e mi ght w ant t o i nst ant i at e a new
Mal l ar dDuc k i nst anc e and i ni t i al i ze i t w i t h a spec i f i c ty pe of
f l y i ng b ehav i or . A nd w hi l e w e’r e t her e, w hy not mak e sur e t hat w e
c an c hange t he b ehav i or of a duc k dy nami c al l y ? In ot her w or ds, w e
shoul d i nc l ude b ehav i or set t er met hods i n t he Duc k c l asses so t hat
w e c an c h ange t he Mal l ar dDuc k ’s f l y i ng b ehav i or at runtim e.

Gi v en t hese goal s, l et ’s l ook at our sec ond desi gn pr i nc i pl e:

W e’l l use an i nt er f ac e t o r epr esent eac h b ehav i or —f or i nst anc e,


Fl y Behav i or and Quac k Behav i or —and eac h i mpl ement at i on of a
beh av ior w i l l i mpl ement one of t hose i nt er f ac es.

So t hi s t i me i t w on’t b e t he Duc k c l asses t hat w i l l i mpl ement t he


f l y i ng and quac k i ng i nt er f ac es. Inst ead, w e’l l mak e a set of c l asses
w hose ent i r e r eason f or l i v i ng i s t o r epr esent a b ehav i or (f or
ex ampl e, “squeak i ng”), and i t ’s t he beh av ior c l ass, r at her t han t he
Duc k c l ass, t hat w i l l i mpl ement t he b ehav i or i nt er f ac e.

Thi s i s i n c ont r ast t o t he w ay w e w er e doi ng t hi ngs b ef or e, w her e a


b ehav i or c ame ei t her f r om a c onc r et e i mpl ement at i on i n t he
super c l ass Duc k , or b y pr ov i di ng a spec i al i zed i mpl ement at i on i n
t he sub c l ass i t sel f . In b ot h c ases w e w er e r el y i ng on an
im plem entation. W e w er e l oc k ed i nt o usi ng t hat spec i f i c
i mpl ement at i on and t her e w as no r oom f or c hangi ng t he b ehav i or
(ot her t han w r i t i ng mor e c ode).

W i t h our new desi gn, t he Duc k sub c l asses w i l l use a b ehav i or


r epr esent ed b y an interfac e (Fl y Behav i or and Quac k Behav i or ), so
t hat t he ac t ual im plem entation of t he b ehav i or (i n ot her w or ds, t he
spec i f i c c onc r et e b ehav i or c oded i n t he c l ass t hat i mpl ement s t he
Fl y Behav i or or Quac k Behav i or ) w on’t b e l oc k ed i nt o t he Duc k
sub c l ass.

Fro m no w o n, th e Duck b e h a v io rs w ill liv e in a


s e p a ra te cla s s —a cla s s th a t im p le m e nts a p a rticula r
b e h a v io r inte rfa ce .

Th a t w a y , th e Duck cla s s e s w o n’t ne e d to k no w a ny o f


th e im p le m e nta tio n d e ta ils fo r th e ir o w n b e h a v io rs .

“Program to an inte rfa ce ” really means “Program to a


s up e rty p e .”

The w or d interfac e i s ov er l oaded her e. Ther e’s t he c onc ept of an


i nt er f ac e, b ut t her e’s al so t he Jav a c ons truc t of an i nt er f ac e. You
c an program to an interfac e w i t hout hav i ng t o ac t ual l y use a Jav a
i nt er f ac e. The poi nt i s t o ex pl oi t pol y mor phi sm b y pr ogr ammi ng
t o a super t y pe so t hat t he ac t ual r unt i me ob jec t i sn’t l oc k ed i nt o
t he c ode. A nd w e c oul d r ephr ase “pr ogr am t o a super t y pe” as “t he
dec l ar ed t y pe of t he v ar i ab l es shoul d b e a super t y pe, usual l y an
ab st r ac t c l ass or i nt er f ac e, so t hat t he ob jec t s assi gned t o t hose
v ar i ab l es c an b e of any c onc r et e i mpl ement at i on of t he super t y pe,
w hi c h means t he c l ass dec l ar i ng t hem doesn’t hav e t o k now ab out
t he ac t ual ob jec t t y pes!”

Thi s i s pr ob ab l y ol d new s t o y ou, b ut just t o mak e sur e w e’r e al l


say i ng t he same t hi ng, her e’s a si mpl e ex ampl e of usi ng a
pol y mor phi c t y pe—i magi ne an ab st r ac t c l ass A ni mal , w i t h t w o
c onc r et e i mpl ement at i ons, Dog and Cat .

Programming to an implementation w oul d b e:

But programming to an interface/superty pe w oul d b e:

Ev en b et t er , r at her t han har dc odi ng t he i nst ant i at i on of t he


sub t y pe (l i k e new Dog()) i nt o t he c ode, assign the concrete
implementation obj ect at runtime:

Implementing the Duck Behaviors


Her e w e hav e t he t w o i nt er f ac es, Fl y Behav i or and Quac k Behav i or ,
al ong w i t h t he c or r espondi ng c l asses t hat i mpl ement eac h c onc r et e
b ehav i or :
there are no Dumb Questions
Q: Do I alway s hav e to implement my application first, see
where things are changing, and then go back to separate and
encapsulate those things?

A: N ot al w ay s; of t en w hen y ou ar e desi gni ng an appl i c at i on, y ou


ant i c i pat e t hose ar eas t hat ar e goi ng t o v ar y and t hen go ahead and
b ui l d t he f l ex i b i l i t y t o deal w i t h i t i nt o y our c ode. You’l l f i nd t hat
t he pr i nc i pl es and pat t er ns c an b e appl i ed at any st age of t he
dev el opment l i f ec y c l e.

Q: Should we make Duck an interface too?

A: N ot i n t hi s c ase. A s y ou’l l see onc e w e’v e got ev er y t hi ng hook ed


t oget her , w e do b enef i t b y hav i ng Duc k not b e an i nt er f ac e, and
hav i ng spec i f i c duc k s, l i k e Mal l ar dDuc k , i nher i t c ommon
pr oper t i es and met hods. N ow t hat w e’v e r emov ed w hat v ar i es f r om
t he Duc k i nher i t anc e, w e get t he b enef i t s of t hi s st r uc t ur e w i t hout
t he pr ob l ems.

Q: I t feels a little weird to hav e a class that’s j ust a behav ior.


Aren’t classes supposed to represent things? Aren’t classes
supposed to hav e both state AND behav ior?

A: In an OO sy st em, y es, c l asses r epr esent t hi ngs t hat gener al l y


hav e b ot h st at e (i nst anc e v ar i ab l es) and met hods. A nd i n t hi s c ase,
t he t hi ng happens t o b e a b ehav i or . But ev en a b ehav i or c an st i l l
hav e st at e and met hods; a f l y i ng b ehav i or mi ght hav e i nst anc e
v ar i ab l es r epr esent i ng t he at t r i b ut es f or t he f l y i ng (w i ng b eat s
per mi nut e, max al t i t ude, speed, et c .) b ehav i or .

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:

1 ) Cr eat e a Fl y Roc k et Pow er ed c l ass t hat i mpl ement s t he


Fl y Behav i or i nt er f ac e.

2) One ex ampl e, a duc k c al l (a dev i c e t hat mak es duc k sounds).

Integrating the Duck Behaviors

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:

1 . F irst we’ll add two instance v ariables of ty pe


F ly Behav ior and QuackBehav ior—l et ’s c al l t hem
f l y Behav i or and quac k Behav i or . Eac h c onc r et e duc k
ob jec t w i l l assi gn t o t hose v ar i ab l es a s pec ific b ehav i or
at r unt i me, l i k e Fl y W i t hW i ngs f or f l y i ng and Squeak f or
quac k i ng.

W e’l l al so r emov e t he f l y () and quac k () met hods f r om t he


Duc k c l ass (and any sub c l asses) b ec ause w e’v e mov ed t hi s
b ehav i or out i nt o t he Fl y Behav i or and Quac k Behav i or
c l asses.
W e’l l r epl ac e f l y () and quac k () i n t he Duc k c l ass w i t h t w o
si mi l ar met hods, c al l ed per f or mFl y () and
per f or mQuac k (); y ou’l l see how t hey w or k nex t .

2. Now we implement performQuack():

Pr et t y si mpl e, huh? To per f or m t he quac k , a Duc k just


ask s t he ob jec t t hat i s r ef er enc ed b y quac k Behav i or t o
quac k f or i t . In t hi s par t of t he c ode w e don’t c ar e w h at
k ind of ob jec t t he c onc r et e Duc k i s, a ll w e ca re a b o ut
is th a t it k no w s h o w to q ua ck ()!

More integration...

3. Ok ay , t i me t o w or r y ab out how t he f l y Behav i or and


quac k Behav i or i nst anc e v ar i ab l es are set. Let ’s t ak e a
l ook at t he Mal l ar dDuc k c l ass:

Mal l ar dDuc k ’s quac k i s a r eal l i v e duc k quack, not a


squeak and not a mute quack. W hen a Mal l ar dDuc k i s
i nst ant i at ed, i t s c onst r uc t or i ni t i al i zes t he
Mal l ar dDuc k ’s i nher i t ed quac k Behav i or i nst anc e
v ar i ab l e t o a new i nst anc e of t y pe Quac k (a
Quac k Behav i or c onc r et e i mpl ement at i on c l ass).

A nd t he same i s t r ue f or t he duc k ’s f l y i ng b ehav i or —t he


Mal l ar dDuc k ’s c onst r uc t or i ni t i al i zes t he i nher i t ed
f l y Behav i or i nst anc e v ar i ab l e w i t h an i nst anc e of t y pe
Fl y W i t hW i ngs (a Fl y Behav i or c onc r et e i mpl ement at i on
c l ass).

Good c at c h, t hat ’s ex ac t l y w hat w e’r e doi ng... for now .

Lat er i n t he b ook w e’l l hav e mor e pat t er ns i n our t ool b ox


t hat c an hel p us f i x i t .

St i l l , not i c e t hat w hi l e w e are set t i ng t he b ehav i or s t o


c onc r et e c l asses (b y i nst ant i at i ng a b ehav i or c l ass l i k e
Quac k or Fl y W i t hW i ngs and assi gni ng i t t o our b ehav i or
r ef er enc e v ar i ab l e), w e c oul d eas ily c hange t hat at
r unt i me.

So, w e st i l l hav e a l ot of f l ex i b i l i t y her e. That sai d, w e’r e


doi ng a poor job of i ni t i al i zi ng t he i nst anc e v ar i ab l es i n a
f l ex i b l e w ay . But t hi nk ab out i t : si nc e t he quac k Behav i or
i nst anc e v ar i ab l e i s an i nt er f ac e t y pe, w e c oul d (t hr ough
t he magi c of pol y mor phi sm) dy nami c al l y assi gn a
di f f er ent Quac k Behav i or i mpl ement at i on c l ass at
r unt i me.

Tak e a moment and t hi nk ab out how y ou w oul d


i mpl ement a duc k so t hat i t s b ehav i or c oul d c hange at
r unt i me. (You’l l see t he c ode t hat does t hi s a f ew pages
f r om now .)
Testing the Duck code

1 . Ty pe and compile the Duck class below (Duck.j av a),


and the MallardDuck class from two pages back
(MallardDuck.j av a).

2. Ty pe and compile the F ly Behav ior interface


(F ly Behav ior.j av a) and the two behav ior
implementation classes (F ly WithWings.j av a and
F ly NoWay .j av a).

3. Ty pe and compile the QuackBehav ior interface


(QuackBehav ior.j av a) and the three behav ior
implementation classes (Quack.j av a,
MuteQuack.j av a, and Squeak.j av a).

4. Ty pe and compile the test class


(MiniDuckSimulator.j av a).

5. Run the code!

Setting behavior dynamically


W hat a shame t o hav e al l t hi s dy nami c t al ent b ui l t i nt o our duc k s
and not b e usi ng i t ! Imagi ne y ou w ant t o set t he duc k ’s b ehav i or
t y pe t hr ough a set t er met hod on t he Duc k c l ass, r at her t han b y
i nst ant i at i ng i t i n t he duc k ’s c onst r uc t or .

1 . Add two new methods to the Duck class:

2. Make a new Duck ty pe (ModelDuck.j av a).


3. Make a new F ly Behav ior ty pe
(F ly RocketPowered.j av a).

4. Change the test class (MiniDuckSimulator.j av a), add


the ModelDuck, and make the ModelDuck rocket-
enabled.

5. Run it!

To ch a ng e a d uck ’s b e h a v io r a t runtim e , jus t ca ll th e


d uck ’s s e tte r m e th o d fo r th a t b e h a v io r.

The Big Picture on encapsulated behaviors


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

Bel ow i s t he ent i r e r ew or k ed c l ass st r uc t ur e. W e hav e ev er y t hi ng


y ou’d ex pec t : duc k s ex t endi ng Duc k , f l y b ehav i or s i mpl ement i ng
Fl y Behav i or , and quac k b ehav i or s i mpl ement i ng Quac k Behav i or .

N ot i c e al so t hat w e’v e st ar t ed t o desc r i b e t hi ngs a l i t t l e


di f f er ent l y . Inst ead of t hi nk i ng of t he duc k b ehav i or s as a s et of
beh av iors , w e’l l st ar t t hi nk i ng of t hem as a fam ily of algorith m s .
Thi nk ab out i t : i n t he Si mU Duc k desi gn, t he al gor i t hms r epr esent
t hi ngs a duc k w oul d do (di f f er ent w ay s of quac k i ng or f l y i ng), b ut
w e c oul d just as easi l y use t he same t ec hni ques f or a set of c l asses
t hat i mpl ement t he w ay s t o c omput e st at e sal es t ax b y di f f er ent
st at es.

Pay c ar ef ul at t ent i on t o t he relations h ips b et w een t he c l asses. In


f ac t , gr ab y our pen and w r i t e t he appr opr i at e r el at i onshi p (IS-A ,
HA S-A , and IMPLEMEN TS) on eac h ar r ow i n t he c l ass di agr am.

N O TE
Make sure you do this.

HAS-A can be better than IS-A


The HA S-A r el at i onshi p i s an i nt er est i ng one: eac h duc k has a
Fl y Behav i or and a Quac k Behav i or t o w hi c h i t del egat es f l y i ng and
quac k i ng.

W hen y ou put t w o c l asses t oget her l i k e t hi s y ou’r e usi ng


composition. Inst ead of inh eriting t hei r b ehav i or , t he duc k s get
t hei r b ehav i or b y b ei ng c om pos ed w i t h t he r i ght b ehav i or ob jec t .
Thi s i s an i mpor t ant t ec hni que; i n f ac t , i t i s t he b asi s of our t hi r d
desi gn pr i nc i pl e:

A s y ou’v e seen, c r eat i ng sy st ems usi ng c omposi t i on gi v es y ou a l ot


mor e f l ex i b i l i t y . N ot onl y does i t l et y ou enc apsul at e a f ami l y of
al gor i t hms i nt o t hei r ow n set of c l asses, b ut i t al so l et s y ou
ch a ng e b e h a v io r a t runtim e as l ong as t he ob jec t y ou’r e
c omposi ng w i t h i mpl ement s t he c or r ec t b ehav i or i nt er f ac e.

Composi t i on i s used i n m any desi gn pat t er ns and y ou’l l see a l ot


mor e ab out i t s adv ant ages and di sadv ant ages t hr oughout t he b ook .

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 and Student...

Guru: Tell me w hat you have learned of the Object-Oriented w ays.

Student: Guru, I have learned that the promise of the object-oriented w ay is


reuse.

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.

Guru: Is more time spent on code before or after development is complete?

Student: The answ er is after, Guru. We alw ays spend more time
maintaining and changing softw are than on initial development.

Guru: So, should effort go into reuse above maintainability and


extensibility?

Student: Guru, I believe that there is truth in this.

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.

Speaking of Design Patterns...

You just appl i ed y our f i r st desi gn pat t er n—t he STRATEGY


Pat t er n. That ’s r i ght , y ou used t he St r at egy Pat t er n t o r ew or k t he
Si mU Duc k app.

Thank s t o t hi s pat t er n, t he si mul at or i s r eady f or any c hanges t hose


ex ec s mi ght c ook up on t hei r nex t b usi ness t r i p t o Maui .

N ow t hat w e’v e made y ou t ak e t he l ong r oad t o l ear n i t , her e’s t he


f or mal def i ni t i on of t hi s pat t er n:

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 ...

(A nsw er s ar e at t he end of t he c hapt er .)

Y our task:

1 . A r r ange t he c l asses.

2. Ident i f y one ab st r ac t c l ass, one i nt er f ac e, and ei ght


c l asses.

3. Dr aw ar r ow s b et w een c l asses.

a. Dr aw t hi s k i nd of ar r ow f or i nher i t anc e (“ex t ends”).

b . Dr aw t hi s k i nd of ar r ow f or i nt er f ac e (“i mpl ement s”).

c . Dr aw t hi s k i nd of ar r ow f or HA S-A .

4. Put t he met hod set W eapon() i nt o t he r i ght c l ass.

Overheard at the local diner...

W hat ’s t he di f f er enc e b et w een t hese t w o or der s? N ot a t hi ng!


They ’r e b ot h t he same or der , ex c ept A l i c e i s usi ng t w i c e t he
numb er of w or ds and t r y i ng t he pat i enc e of a gr umpy shor t -or der
c ook .

W hat ’s Fl o got t hat A l i c e doesn’t ? A shared v ocabulary w i t h t he


shor t -or der c ook . N ot onl y does t hat mak e i t easi er t o c ommuni c at e
w i t h t he c ook , b ut i t gi v es t he c ook l ess t o r ememb er b ec ause he’s
got al l t he di ner pat t er ns i n hi s head.

Desi gn Pat t er ns gi v e y ou a shar ed v oc ab ul ar y w i t h ot her


dev el oper s. Onc e y ou’v e got t he v oc ab ul ar y , y ou c an mor e easi l y
c ommuni c at e w i t h ot her dev el oper s and i nspi r e t hose w ho don’t
k now pat t er ns t o st ar t l ear ni ng t hem. It al so el ev at es y our
t hi nk i ng ab out ar c hi t ec t ur es b y l et t i ng y ou think at the p a tte rn
lev el, not t he ni t t y -gr i t t y objec t l ev el .

Overheard in the next cubicle...


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

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

The power of a shared pattern vocabulary


When y ou communicate using patterns, y ou are doing more
than j ust sharing LI NGO.

Shared pattern v ocabularies are POWERF UL. W hen y ou


c ommuni c at e w i t h anot her dev el oper or y our t eam usi ng pat t er ns,
y ou ar e c ommuni c at i ng not just a pat t er n name b ut a w hol e set of
qual i t i es, c har ac t er i st i c s, and c onst r ai nt s t hat t he pat t er n
r epr esent s.

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.

Patterns allow y ou to say more with less. W hen y ou use a pat t er n


i n a desc r i pt i on, ot her dev el oper s qui c k l y k now pr ec i sel y t he
desi gn y ou hav e i n mi nd.

Talking at the pattern lev el allows y ou to stay “in the design”


longer. Tal k i ng ab out sof t w ar e sy st ems usi ng pat t er ns al l ow s y ou
t o k eep t he di sc ussi on at t he desi gn l ev el , w i t hout hav i ng t o di v e
dow n t o t he ni t t y -gr i t t y det ai l s of i mpl ement i ng ob jec t s and
c l asses.

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

Shared v ocabularies can turbo-charge y our dev elopment team.


A t eam w el l v er sed i n desi gn pat t er ns c an mov e mor e qui c k l y w i t h
l ess r oom f or mi sunder st andi ng.
N O TE
As your team begins to share design ideas and experience in
terms of patterns, you will build a community of pattern users.

Shared v ocabularies encourage more j unior dev elopers to get


up to speed. Juni or dev el oper s l ook up t o ex per i enc ed dev el oper s.
W hen seni or dev el oper s mak e use of desi gn pat t er ns, juni or
dev el oper s al so b ec ome mot i v at ed t o l ear n t hem. Bui l d a
c ommuni t y of pat t er n user s at y our or gani zat i on.

N O TE
Think about starting a patterns study group at your
organization. Maybe you can even get paid while you’re
learning...

How do I use Design Patterns?


W e’v e al l used of f -t he-shel f l i b r ar i es and f r amew or k s. W e t ak e
t hem, w r i t e some c ode agai nst t hei r A PIs, c ompi l e t hem i nt o our
pr ogr ams, and b enef i t f r om a l ot of c ode someone el se has w r i t t en.
Thi nk ab out t he Jav a A PIs and al l t he f unc t i onal i t y t hey gi v e y ou:
net w or k , GU I, IO, et c . Li b r ar i es and f r amew or k s go a l ong w ay
t ow ar d a dev el opment model w her e w e c an just pi c k and c hoose
c omponent s and pl ug t hem r i ght i n. But ...t hey don’t hel p us
st r uc t ur e our ow n appl i c at i ons i n w ay s t hat ar e easi er t o
under st and, mor e mai nt ai nab l e, and mor e f l ex i b l e. That ’s w her e
desi gn pat t er ns c ome i n.

Desi gn pat t er ns don’t go di r ec t l y i nt o y our c ode, t hey f i r st go i nt o


y our BRA IN . Onc e y ou’v e l oaded y our b r ai n w i t h a good w or k i ng
k now l edge of pat t er ns, y ou c an t hen st ar t t o appl y t hem t o y our
new desi gns, and r ew or k y our ol d c ode w hen y ou f i nd i t ’s degr adi ng
i nt o an i nf l ex i b l e mess.

there are no Dumb Questions


Q: I f design patterns are so great, why can’t someone build a
library of them so I don’t hav e to?

A: Desi gn pat t er ns ar e hi gher l ev el t han l i b r ar i es. Desi gn pat t er ns


t el l us how t o st r uc t ur e c l asses and ob jec t s t o sol v e c er t ai n
pr ob l ems, and i t i s our job t o adapt t hose desi gns t o f i t our
par t i c ul ar appl i c at i on.

Q: Aren’t libraries and frameworks also design patterns?

A: Fr amew or k s and l i b r ar i es ar e not desi gn pat t er ns; t hey pr ov i de


spec i f i c i mpl ement at i ons t hat w e l i nk i nt o our c ode. Somet i mes,
how ev er , l i b r ar i es and f r amew or k s mak e use of desi gn pat t er ns i n
t hei r i mpl ement at i ons. That ’s gr eat , b ec ause onc e y ou under st and
desi gn pat t er ns, y ou’l l mor e qui c k l y under st and A PIs t hat ar e
st r uc t ur ed ar ound desi gn pat t er ns.

Q: So, there are no libraries of design patterns?

A: N o, b ut y ou w i l l l ear n l at er ab out pat t er ns c at al ogs w i t h l i st s of


pat t er ns t hat y ou c an appl y t o y our appl i c at i ons.

Dev eloper: Ok ay , hmm, b ut i sn’t t hi s al l just good ob jec t -or i ent ed


desi gn; I mean as l ong as I f ol l ow enc apsul at i on and I k now ab out
ab st r ac t i on, i nher i t anc e, and pol y mor phi sm, do I r eal l y need t o
t hi nk ab out Desi gn Pat t er ns? Isn’t i t pr et t y st r ai ght f or w ar d? Isn’t
t hi s w hy I t ook al l t hose OO c our ses? I t hi nk Desi gn Pat t er ns ar e
usef ul f or peopl e w ho don’t k now good OO desi gn.

Guru: A h, t hi s i s one of t he t r ue mi sunder st andi ngs of ob jec t -


or i ent ed dev el opment : t hat b y k now i ng t he OO b asi c s w e ar e
aut omat i c al l y goi ng t o b e good at b ui l di ng f l ex i b l e, r eusab l e, and
mai nt ai nab l e sy st ems.

Dev eloper: N o?

Guru: N o. A s i t t ur ns out , c onst r uc t i ng OO sy st ems t hat hav e t hese


pr oper t i es i s not al w ay s ob v i ous and has b een di sc ov er ed onl y
t hr ough har d w or k .

Dev eloper: I t hi nk I’m st ar t i ng t o get i t . These, somet i mes non-


ob v i ous, w ay s of c onst r uc t i ng ob jec t -or i ent ed sy st ems hav e b een
c ol l ec t ed...

Guru: ...y es, i nt o a set of pat t er ns c al l ed Desi gn Pat t er ns.

Dev eloper: So, b y k now i ng pat t er ns, I c an sk i p t he har d w or k and


jump st r ai ght t o desi gns t hat al w ay s w or k ?

Guru: Yes, t o an ex t ent , b ut r ememb er , desi gn i s an ar t . Ther e w i l l


al w ay s b e t r adeof f s. But , i f y ou f ol l ow w el l -t hought -out and t i me-
t est ed desi gn pat t er ns, y ou’l l b e w ay ahead.

Dev eloper: W hat do I do i f I c an’t f i nd a pat t er n?

Guru: Ther e ar e some ob jec t -or i ent ed pr i nc i pl es t hat under l i e t he


pat t er ns, and k now i ng t hese w i l l hel p y ou t o c ope w hen y ou c an’t
f i nd a pat t er n t hat mat c hes y our pr ob l em.

Dev eloper: Pr i nc i pl es? You mean b ey ond ab st r ac t i on,


enc apsul at i on, and...

Guru: Yes, one of t he sec r et s t o c r eat i ng mai nt ai nab l e OO sy st ems i s


t hi nk i ng ab out how t hey mi ght c hange i n t he f ut ur e, and t hese
pr i nc i pl es addr ess t hose i ssues.

Tools for your Design Toolbox


You’v e near l y made i t t hr ough t he f i r st c hapt er ! You’v e al r eady put
a f ew t ool s i n y our OO t ool b ox ; l et ’s mak e a l i st of t hem b ef or e w e
mov e on t o Chapt er 2.
B U L L ET PO IN T S

Knowing the OO basics does not make you a good OO designer.

Good OO designs are reusable, extensible, and maintainable.

Patterns show you how to build systems with good OO design


qualities.

Patterns are proven object-oriented experience.

Patterns don’t give you code, they give you general solutions to
design problems. You apply them to your specific application.

Patterns aren’t invented, they are discovered.

Most patterns and principles address issues of change in


software.

Most patterns allow some part of a system to vary independently


of all other parts.

We often try to take what varies in a system and encapsulate it.

Patterns provide a shared language that can maximize the value


of your communication with other developers.

Design Patterns Crossword


Let ’s gi v e y our r i ght b r ai n somet hi ng t o do.

It ’s y our st andar d c r ossw or d; al l of t he sol ut i on w or ds ar e f r om t hi s


c hapt er .

ACROSS

1 . Paat t er ns c an hel p us b ui l d ________ appl i c at i ons.

4. St r at egi es c an b e __________.

7 . Fav or t hi s ov er i nher i t anc e.

8. Dev el opment c onst ant .

9. Jav a IO, N et w or k i ng, Sound.

1 0. Most pat t er ns f ol l ow f r om OO _________.

1 2. Desi gn pat t er ns ar e a shar ed __________.


1 4. Hi gh-l ev el l i b r ar i es.

1 5. Lear n f r om t he ot her guy ’s ___________.

1 7 . Pat t er n t hat f i x ed t he si mul at or .

1 8. Pr ogr am t o t hi s, not an i mpl ement at i on.

DOWN

2. Pat t er ns go i nt o y our _______.

3. Duc k t hat c an’t quac k .

5. Rub b er duc k s mak e a _______.

6. ________ w hat v ar i es.

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.

1 6. Duc k demo w as l oc at ed her e.

Design Puzzle Solution


Char ac t er i s t he ab st r ac t c l ass f or al l t he ot her c har ac t er s (Ki ng,
Queen, Kni ght , and Tr ol l ), w hi l e W eaponBehav i or i s an i nt er f ac e
t hat al l w eapon b ehav i or s i mpl ement . So al l ac t ual c har ac t er s and
w eapons ar e c onc r et e c l asses.

To sw i t c h w eapons, eac h c har ac t er c al l s t he set W eapon() met hod,


w hi c h i s def i ned i n t he Char ac t er super c l ass. Dur i ng a f i ght t he
useW eapon() met hod i s c al l ed on t he c ur r ent w eapon set f or a gi v en
c har ac t er t o i nf l i c t gr eat b odi l y damage on anot her c har ac t er .

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.

A. Code is duplicated across subclasses.

B. Runtime behavior changes are difficult.

C. We can’t make ducks dance.

D. It’s hard to gain knowledge of all duck behaviors.

E. Ducks can’t fly and quack at the same time.

F. Changes can unintentionally affect other ducks.


SH AR PEN YO U R PEN C IL
SO L U T IO N
What are some factors that drive change in your applications? You might
have a very different list, but here’s a few of ours. Look familiar? Here’s our
solution.

My customers or users decide they want something else, or they want new
functionality.

My company decided it is going with another database vendor and it is also


purchasing its data from another supplier that uses a different data format.
Argh!

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.

Design Patterns Crossword Solution


Chapter 2. Keeping your Objects in
the Know: The Observer Pattern

Y ou don’t want to miss out when something interesting


happens, do y ou? W e’v e got a pat t er n t hat k eeps y our ob jec t s in
th e k now w hen somet hi ng t hey c are about happens. It ’s t he
Ob ser v er Pat t er n. It i s one of t he most c ommonl y used desi gn
pat t er ns, and i t ’s i nc r edi b l y usef ul . W e’r e goi ng t o l ook at al l k i nds
of i nt er est i ng aspec t s of Ob ser v er , l i k e i t s one-to-m any
relations h ips and loos e c oupling. A nd, w i t h t hose c onc ept s i n mi nd,
how c an y ou hel p b ut b e t he l i f e of t he Pat t er ns Par t y ?

Congratulations!

Y our team has j ust won the contract to build Weather-O-Rama,


I nc.’s next-generation, internet-based Weather Monitoring
Station.

The Weather Monitoring application overview


Let ’s t ak e a l ook at t he W eat her Moni t or i ng appl i c at i on w e need t o
del i v er —b ot h w hat W eat her -O-Rama i s gi v i ng us, and w hat w e’r e
goi ng t o need t o b ui l d or ex t end. The sy st em has t hr ee c omponent s:
t he w eat her st at i on (t he phy si c al dev i c e t hat ac qui r es t he ac t ual
w eat her dat a), t he W eat her Dat a ob jec t (t hat t r ac k s t he dat a c omi ng
f r om t he W eat her St at i on and updat es t he di spl ay s), and t he di spl ay
t hat show s user s t he c ur r ent w eat her c ondi t i ons:

The W eat her Dat a ob jec t w as w r i t t en b y W eat her -O-Rama and


k now s how t o t al k t o t he phy si c al W eat her St at i on t o get updat ed
w eat her dat a. W e’l l need t o adapt t he W eat her Dat a ob jec t so t hat i t
k now s how t o updat e t he di spl ay . Hopef ul l y W eat her -O-Rama has
gi v en us hi nt s f or how t o do t hi s i n t he sour c e c ode. Rememb er ,
w e’r e r esponsi b l e f or i mpl ement i ng t hr ee di f f er ent di spl ay
el ement s: Cur r ent Condi t i ons (show s t emper at ur e, humi di t y , and
pr essur e), W eat her St at i st i c s, and a si mpl e For ec ast .

So, our j ob, if we choose to accept it, is to create an app that


uses the WeatherData obj ect to update three display s for
current conditions, weather stats, and a forecast.

Unpacking the WeatherData class


Let’s check out the source code attachments that Johnny
Hurricane, the CEO, sent ov er. We’ll start with the WeatherData
class:

So, our j ob is to alter the measurementsChanged() method so


that it updates the three display s for current conditions,
weather stats, and forecast.

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:

W e k now t he W eat her Dat a c l ass has get t er met hods f or


t hr ee measur ement v al ues: t emper at ur e, humi di t y , and
b ar omet r i c pr essur e.

W e k now t he measur ement sChanged() met hod i s c al l ed


any t i me new w eat her measur ement dat a i s av ai l ab l e.
(A gai n, w e don’t k now or c ar e how t hi s met hod i s c al l ed;
w e just k now t hat i t is c alled.)

W e’l l need t o i mpl ement t hr ee di spl ay el ement s t hat use


t he w eat her dat a: a c urrent c onditions di spl ay , a s tatis tic s
dis play , and a forec as t di spl ay . These di spl ay s must b e
updat ed as of t en as t he W eat her Dat a has new
measur ement s.

To updat e t he di spl ay s, w e’l l add c ode t o t he


measur ement sChanged() met hod.
Stretch Goal
But l et ’s al so t hi nk ab out t he f ut ur e—r ememb er t he c onst ant i n
sof t w ar e dev el opment ? Change. W e ex pec t , i f t he W eat her St at i on
i s suc c essf ul , t her e w i l l b e mor e t han t hr ee di spl ay s i n t he f ut ur e,
so w hy not c r eat e a mar k et pl ac e f or addi t i onal di spl ay s? So, how
ab out w e b ui l d i n:

Ex pandab i l i t y —ot her dev el oper s may w ant t o c r eat e new


c ust om di spl ay s. W hy not al l ow user s t o add (or r emov e)
as many di spl ay el ement s as t hey w ant t o t he
appl i c at i on? Cur r ent l y , w e k now ab out t he i ni t i al th ree
di spl ay t y pes (c ur r ent c ondi t i ons, st at i st i c s, and
f or ec ast ), b ut w e ex pec t a v i b r ant mar k et pl ac e f or new
di spl ay s i n t he f ut ur e.

Taking a first, misguided implementation of the Weather


Station
Her e’s a f i r st i mpl ement at i on possi b i l i t y —as w e’v e di sc ussed,
w e’r e goi ng t o add our c ode t o t he measur ement sChanged() met hod
i n t he W eat her Dat a c l ass:
SH AR PEN YO U R PEN C IL
Based on our first implementation, which of the following apply? (Choose
all that apply.)

A. We are coding to concrete implementations, not interfaces.

B. For every new display we’ll need to alter this code.

C. We have no way to add (or remove) display elements at runtime.

D. T he display elements don’t implement a common interface.

E. We haven’t encapsulated the part that changes.

F. We are violating encapsulation of the WeatherData class.

What’s wrong with our implementation anyway?


Thi nk b ac k t o al l t hose Chapt er 1 c onc ept s and pr i nc i pl es—w hi c h
ar e w e v i ol at i ng, and w hi c h ar e w e not ? Thi nk i n par t i c ul ar ab out
t he ef f ec t s of c hange on t hi s c ode. Let ’s w or k t hr ough our t hi nk i ng
as w e l ook at t he c ode:

Good i dea. Let ’s t ak e a l ook at Ob ser v er , t hen c ome b ac k and f i gur e


out how t o appl y i t t o t he W eat her Moni t or i ng app.

Meet the Observer Pattern


Y ou know how newspaper or magazine subscriptions work:

1 . A new spaper pub l i sher goes i nt o b usi ness and b egi ns


pub l i shi ng new spaper s.

2. You sub sc r i b e t o a par t i c ul ar pub l i sher , and ev er y t i me


t her e’s a new edi t i on i t get s del i v er ed t o y ou. A s l ong as
y ou r emai n a sub sc r i b er , y ou get new new spaper s.

3. You unsub sc r i b e w hen y ou don’t w ant paper s any mor e,


and t hey st op b ei ng del i v er ed.

4. W hi l e t he pub l i sher r emai ns i n b usi ness, peopl e, hot el s,


ai r l i nes, and ot her b usi nesses c onst ant l y sub sc r i b e and
unsub sc r i b e t o t he new spaper .
Publishers + Subscribers = Observer Pattern
I f y ou understand newspaper subscriptions, y ou pretty much
understand the Observ er Pattern, only we call the publisher the
SUBJECT and the subscribers the OBSERVERS.

Let’s take a closer look:

A day in the life of the Observer Pattern


A Duck obj ect comes along and tells the Subj ect that he wants
to become an observ er.

Duc k r eal l y w ant s i n on t he ac t i on; t hose i nt s Sub jec t i s sendi ng out


w henev er i t s st at e c hanges l ook pr et t y i nt er est i ng...

The Duck obj ect is now an official observ er.

Duc k i s psy c hed...he’s on t he l i st and i s w ai t i ng w i t h gr eat


ant i c i pat i on f or t he nex t not i f i c at i on so he c an get an i nt .

The Subj ect gets a new data v alue!

N ow Duc k and al l t he r est of t he ob ser v er s get a not i f i c at i on t hat


t he Sub jec t has c hanged.
The Mouse obj ect asks to be remov ed as an observ er.

The Mouse ob jec t has b een get t i ng i nt s f or ages and i s t i r ed of i t , so


he dec i des i t ’s t i me t o st op b ei ng an ob ser v er .

Mouse is outta here!

The Sub jec t ac k now l edges t he Mouse’s r equest and r emov es hi m


f r om t he set of ob ser v er s.

The Subj ect has another new int.

A l l t he ob ser v er s get anot her not i f i c at i on, ex c ept f or t he Mouse


w ho i s no l onger i nc l uded. Don’t t el l any one, b ut t he Mouse sec r et l y
mi sses t hose i nt s... may b e he’l l ask t o b e an ob ser v er agai n some day .

Five-minute drama: a subject for


observation
In t oday ’s sk i t , t w o ent er pr i si ng sof t w ar e dev el oper s enc ount er a
r eal l i v e head hunt er ...

1 . Software Dev eloper #1


2. Headhunter/Subj ect

3. Software Dev eloper #2

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

Ji l l l ands her ow n job !

9. Subj ect

Two weeks later...


Ji l l ’s l ov i ng l i f e, and no l onger an ob ser v er . She’s al so enjoy i ng t he
ni c e f at si gni ng b onus t hat she got b ec ause t he c ompany di dn’t hav e
t o pay a headhunt er .
But w hat has b ec ome of our dear Lor i ? W e hear she’s b eat i ng t he
headhunt er at hi s ow n game. She’s not onl y st i l l an ob ser v er , she’s
got her ow n c al l l i st now , and she i s not i f y i ng her ow n ob ser v er s.
Lor i ’s a sub jec t and an ob ser v er al l i n one.

The Observer Pattern defined


A new spaper sub sc r i pt i on, w i t h i t s pub l i sher and sub sc r i b er s, i s a
good w ay t o v i sual i ze t he pat t er n.

In t he r eal w or l d, how ev er , y ou’l l t y pi c al l y see t he Ob ser v er


Pat t er n def i ned l i k e t hi s:

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.

Let ’s r el at e t hi s def i ni t i on t o how w e’v e b een t hi nk i ng ab out t he


pat t er n:
Th e Ob s e rv e r Pa tte rn d e fine s a o ne -to -m a ny
re la tio ns h ip b e tw e e n a s e t o f o b je cts .

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 .

The sub jec t and ob ser v er s def i ne t he one-t o-many r el at i onshi p. W e


hav e one s ubjec t, w ho not i f i es m any obs erv ers w hen somet hi ng i n
t he sub jec t c hanges. The ob ser v er s are dependent on t he sub jec t —
w hen t he sub jec t ’s st at e c hanges, t he ob ser v er s ar e not i f i ed.

A s y ou’l l di sc ov er , t her e ar e a f ew di f f er ent w ay s t o i mpl ement t he


Ob ser v er Pat t er n, b ut most r ev ol v e ar ound a c l ass desi gn t hat
i nc l udes Sub jec t and Ob ser v er i nt er f ac es.

The Observer Pattern: the Class Diagram


Let ’s t ak e a l ook at t he st r uc t ur e of t he Ob ser v er Pat t er n, c ompl et e
w i t h i t s Sub jec t and Ob ser v er c l asses. Her e’s t he c l ass di agr am:

there are no Dumb Questions


Q: What does this hav e to do with one-to-many relationships?

A: W i t h t he Ob ser v er Pat t er n, t he Sub jec t i s t he ob jec t t hat


c ont ai ns t he st at e and c ont r ol s i t . So, t her e i s ON E sub jec t w i t h
st at e. The ob ser v er s, on t he ot her hand, use t he st at e, ev en i f t hey
don’t ow n i t . Ther e ar e many ob ser v er s, and t hey r el y on t he
Sub jec t t o t el l t hem w hen i t s st at e c hanges. So t her e i s a
r el at i onshi p b et w een t he ON E Sub jec t t o t he MA N Y Ob ser v er s.

Q: How does dependence come into this?

A: Bec ause t he sub jec t i s t he sol e ow ner of t hat dat a, t he ob ser v er s


ar e dependent on t he sub jec t t o updat e t hem w hen t he dat a c hanges.
Thi s l eads t o a c l eaner OO desi gn t han al l ow i ng many ob jec t s t o
c ont r ol t he same dat a.

Q: I ’v e also heard of a Publish-Subscribe Pattern. I s that j ust


another name for the Observ er Pattern?

A: N o, al t hough t hey ar e r el at ed. The Pub l i sh-Sub sc r i b e pat t er n i s


a mor e c ompl ex pat t er n t hat al l ow s sub sc r i b er s t o ex pr ess i nt er est
i n di f f er ent t y pes of messages and f ur t her separ at es pub l i sher s
f r om sub sc r i b er s. It i s of t en used i n mi ddl ew ar e sy st ems.
G U R U AN D ST U D EN T

Guru and Student...

Guru: Have w e talked about loose coupling?

Student: Guru, I do not recall such a discussion.

Guru: Is a tightly w oven basket stiff or flexible?

Student: Stiff, Guru.

Guru: And do stiff or flexible baskets tear or break less easily?

Student: A flexible basket tends to break less easily.

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?

Guru: We like to call it, loosely coupled.

Student: Ah!

Guru: We say a object is tightly coupled to another object w hen it is too


dependent on that object.

Student: So a loosely coupled object can’t depend on another object?

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.

Student: Of course, I am sure you are right. Could you give me an


example?

Guru: That is enough for today.

The Power of Loose Coupling


W hen t w o ob jec t s ar e loos ely c oupled, t hey c an i nt er ac t , b ut t hey
t y pi c al l y hav e v er y l i t t l e k now l edge of eac h ot her . A s w e’r e goi ng
t o see, l oosel y c oupl ed desi gns of t en gi v e us a l ot of f l ex i b i l i t y
(mor e on t hat i n a b i t ). A nd, as i t t ur ns out , t he Ob ser v er Pat t er n i s a
gr eat ex ampl e of l oose c oupl i ng. Let ’s w al k t hr ough al l t he w ay s
t he pat t er n ac hi ev es l oose c oupl i ng:

F irst, the only thing the subj ect knows about an


observ er is that it implements a certain interface (the
Observ er interface). It doesn’t need t o k now t he c onc r et e
c l ass of t he ob ser v er , w hat i t does, or any t hi ng el se ab out
i t.

We can add new observ ers at any time. Bec ause t he


onl y t hi ng t he sub jec t depends on i s a l i st of ob jec t s t hat
i mpl ement t he Ob ser v er i nt er f ac e, w e c an add new
ob ser v er s w henev er w e w ant . In f ac t , w e c an r epl ac e any
ob ser v er at r unt i me w i t h anot her ob ser v er and t he
sub jec t w i l l k eep pur r i ng al ong. Li k ew i se, w e c an r emov e
ob ser v er s at any t i me.

We nev er need to modify the subj ect to add new ty pes


of observ ers. Let ’s say w e hav e a new c onc r et e c l ass c ome
al ong t hat needs t o b e an ob ser v er . W e don’t need t o mak e
any c hanges t o t he sub jec t t o ac c ommodat e t he new c l ass
t y pe; al l w e hav e t o do i s i mpl ement t he Ob ser v er
i nt er f ac e i n t he new c l ass and r egi st er as an ob ser v er .
The sub jec t doesn’t c ar e; i t w i l l del i v er not i f i c at i ons t o
any ob jec t t hat i mpl ement s t he Ob ser v er i nt er f ac e.

We can reuse subj ects or observ ers independently of


each other. If w e hav e anot her use f or a sub jec t or an
ob ser v er , w e c an easi l y r euse t hem b ec ause t he t w o ar en’t
t i ght l y c oupl ed.

Changes to either the subj ect or an observ er will not


affect the other. Bec ause t he t w o ar e l oosel y c oupl ed, w e
ar e f r ee t o mak e c hanges t o ei t her , as l ong as t he ob jec t s
st i l l meet t hei r ob l i gat i ons t o i mpl ement t he Sub jec t or
Ob ser v er i nt er f ac es.

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...

Mary : W el l , i t hel ps t o k now w e’r e usi ng t he Ob ser v er


Pat t er n.

Sue: Ri ght ...b ut how do w e appl y i t ?

Mary : Hmm. Let ’s l ook at t he def i ni t i on agai n:

Th e Obs erv er Pattern defines a one-to-m any dependenc y


betw een objec ts s o th at w h en one objec t c h anges s tate, all
its dependents are notified and updated autom atic ally .

Mary : That ac t ual l y mak es some sense w hen y ou t hi nk


ab out i t . Our W eat her Dat a c l ass i s t he “one,” and our
“many ” i s t he v ar i ous di spl ay el ement s t hat use t he
w eat her measur ement s.

Sue: That ’s r i ght . The W eat her Dat a c l ass c er t ai nl y has


st at e...t hat ’s t he t emper at ur e, humi di t y , and b ar omet r i c
pr essur e, and t hose def i ni t el y c hange.

Mary : Yup, and w hen t hose measur ement s c hange, w e


hav e t o not i f y al l t he di spl ay el ement s so t hey c an do
w hat ev er i t i s t hey ar e goi ng t o do w i t h t he
measur ement s.

Sue: Cool , now I t hi nk I see how t he Ob ser v er Pat t er n c an


b e appl i ed t o our W eat her St at i on pr ob l em.

Mary : Ther e ar e st i l l a f ew t hi ngs t o c onsi der t hat I’m not


sur e I under st and y et .

Sue: Li k e w hat ?

Mary : For one t hi ng, how do w e get t he w eat her


measur ement s t o t he di spl ay el ement s?

Sue: W el l , l ook i ng b ac k at t he pi c t ur e of t he Ob ser v er


Pat t er n, i f w e mak e t he W eat her Dat a ob jec t t he sub jec t ,
and t he di spl ay el ement s t he ob ser v er s, t hen t he di spl ay s
w i l l r egi st er t hemsel v es w i t h t he W eat her Dat a ob jec t i n
or der t o get t he i nf or mat i on t hey w ant , r i ght ?

Mary : Yes...and onc e t he W eat her St at i on k now s ab out a


di spl ay el ement , t hen i t c an just c al l a met hod t o t el l i t
ab out t he measur ement s.

Sue: W e got t a r ememb er t hat ev er y di spl ay el ement c an


b e di f f er ent ...so I t hi nk t hat ’s w her e hav i ng a c ommon
i nt er f ac e c omes i n. Ev en t hough ev er y c omponent has a
di f f er ent t y pe, t hey shoul d al l i mpl ement t he same
i nt er f ac e so t hat t he W eat her Dat a ob jec t w i l l k now how
t o send t hem t he measur ement s.

Mary : I see w hat y ou mean. So ev er y di spl ay w i l l hav e,


say , an updat e() met hod t hat W eat her Dat a w i l l c al l .

Sue: A nd updat e() i s def i ned i n a c ommon i nt er f ac e t hat


al l t he el ement s i mpl ement …

Designing the Weather Station


How does t hi s di agr am c ompar e w i t h y our s?

Implementing the Weather Station


A l l r i ght , w e’v e had some gr eat t hi nk i ng f r om Mar y and Sue (f r om a
f ew pages b ac k ) and w e’v e got a di agr am t hat det ai l s t he ov er al l
st r uc t ur e of our c l asses. So, l et ’s get our i mpl ement i on of t he
w eat her st at i on under w ay . Let ’s st ar t w i t h t he i nt er f ac es:

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.

Implementing the Subject interface in WeatherData


Rememb er our f i r st at t empt at i mpl ement i ng t he W eat her Dat a
c l ass at t he b egi nni ng of t he c hapt er ? You mi ght w ant t o r ef r esh
y our memor y . N ow i t ’s t i me t o go b ac k and do t hi ngs w i t h t he
Ob ser v er Pat t er n i n mi nd:
N O TE
REMEMBER: we don’t provide import and package statements
in the code listings. Get the complete source code from
https://wickedlysmart.com/head-first-design-patterns

Now, let’s build those display elements


N ow t hat w e’v e got our W eat her Dat a c l ass st r ai ght ened out , i t ’s
t i me t o b ui l d t he di spl ay el ement s. W eat her -O-Rama or der ed t hr ee:
t he c ur r ent c ondi t i ons di spl ay , t he st at i st i c s di spl ay , and t he
f or ec ast di spl ay . Let ’s t ak e a l ook at t he c ur r ent c ondi t i ons di spl ay ;
onc e y ou hav e a good f eel f or t hi s di spl ay el ement , c hec k out t he
st at i st i c s and f or ec ast di spl ay s i n t he c ode di r ec t or y . You’l l see
t hey ar e v er y si mi l ar .

there are no Dumb Questions


Q: I s update() the best place to call display ()?

A: In t hi s si mpl e ex ampl e i t made sense t o c al l di spl ay () w hen t he


v al ues c hanged. How ev er , y ou’r e r i ght ; t her e ar e muc h b et t er w ay s
t o desi gn t he w ay t he dat a get s di spl ay ed. W e’l l see t hi s w hen w e get
t o t he Model -V i ew -Cont r ol l er pat t er n.

Q: Why did y ou store a reference to the WeatherData Subj ect?


I t doesn’t look like y ou use it again after the constructor.

A: Tr ue, b ut i n t he f ut ur e w e may w ant t o un-r egi st er our sel v es as


an ob ser v er and i t w oul d b e handy t o al r eady hav e a r ef er enc e t o
t he sub jec t .

Power up the Weather Station

1 . F irst, let’s create a test harness.

The W eat her St at i on i s r eady t o go. A l l w e need i s some


c ode t o gl ue ev er y t hi ng t oget her . W e’l l b e addi ng some
mor e di spl ay s and gener al i zi ng t hi ngs i n a b i t . For now ,
her e’s our f i r st at t empt :
2. Run the code and let the Observ er Pattern do its magic.

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.

T he heat index is an index that combines temperature and humidity to


determine the apparent temperature (how hot it actually feels). To compute
the heat index, you take the temperature, T, and the relative humidity, RH,
and use this formula:

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).

When you finish, your output should look like this:

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:

I’m glad we’re finally


getting a chance to chat in
person.

Really? I thought you didn’t care much about us


Observers.

Well, I do my job, don’t I?


I always tell you what’s
going on... Just because I
don’t really know who you
are doesn’t mean I don’t
care. And besides, I do
know the most important
thing about you—you
implement the Observer
interface.

Yeah, but that’s just a small part of who I am. Anyway, I


know a lot more about you...

Oh yeah, like what?

Well, you’re always passing your state around to us


Observers so we can see what’s going on inside you.
Which gets a little annoying at times...

Well, excuuuse me. I have


to send my state with my
notifications so all you lazy
Observers will know what
happened!

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?

Well...I guess that might


work. I’d have to open
myself up even more,
though, to let all you
Observers come in and get
the state that you need. That
might be kind of
dangerous. I can’t let you
come in and just snoop
around looking at
everything I’ve got.

Why don’t you just write some public getter methods that
will let us pull out the state we need?

Yes, I could let you pull my


state. But won’t that be less
convenient for you? If you
have to come to me every
time you want something,
you might have to make
multiple method calls to get
all the state you want.
That’s why I like push
better...then you have
everything you need in one
notification.

Don’t be so pushy! There are so many different kinds of


us Observers, there’s no way you can anticipate
everything we need. Just let us come to you to get the state
we need. That way, if some of us only need a little bit of
state, we aren’t forced to get it all. It also makes things
easier to modify later. Say, for example, you expand
yourself and add some more state. If you use pull, you
don’t have to go around and change the update calls on
every observer; you just need to change yourself to allow
more getter methods to access our additional state.

Well, as I like to say, don’t


call us, we’ll call you! But
I’ll give it some thought.

I won’t hold my breath.

You never know, hell could


freeze over.

I see, always the wise guy...

Indeed.

Looking for the Observer Pattern in the Wild


The Ob ser v er Pat t er n i s one of t he most c ommon pat t er ns i n use,
and y ou’l l f i nd pl ent y of ex ampl es of t he pat t er n b ei ng used i n
many l i b r ar i es and f r amew or k s. If w e l ook at t he Jav a
Dev el opment Ki t (JDK), f or i nst anc e, b ot h t he Jav aBeans and Sw i ng
l i b r ar i es mak e use of t he Ob ser v er Pat t er n. The pat t er n’s not
l i mi t ed t o Jav a ei t her ; i t ’s used i n Jav aSc r i pt ’s ev ent s and i n Coc oa
and Sw i f t ’s Key -V al ue Ob ser v i ng pr ot oc ol , t o name a c oupl e of
ot her ex ampl es. One of t he adv ant ages of k now i ng desi gn pat t er ns
i s r ec ogni zi ng and qui c k l y under st andi ng t he desi gn mot i v at i on i n
y our f av or i t e l i b r ar i es. Let ’s t ak e a qui c k di v er si on i nt o t he Sw i ng
l i b r ar y t o see how Ob ser v er i s used.
The Swing library

You pr ob ab l y al r eady k now t hat Sw i ng i s Jav a’s GU I t ool k i t f or


user i nt er f ac es. One of t he most b asi c c omponent s of t hat t ool k i t i s
t he JBut t on c l ass. If y ou l ook up JBut t on’s super c l ass,
A b st r ac t But t on, y ou’l l f i nd t hat i t has a l ot of add/r emov e l i st ener
met hods. These met hods al l ow y ou t o add and r emov e ob ser v er s—or ,
as t hey ar e c al l ed i n Sw i ng, l i st ener s—t o l i st en f or v ar i ous t y pes of
ev ent s t hat oc c ur on t he Sw i ng c omponent . For i nst anc e, an
A c t i onLi st ener l et s y ou “l i st en i n” on any t y pes of ac t i ons t hat
mi ght oc c ur on a b ut t on, l i k e a b ut t on pr ess. You’l l f i nd v ar i ous
t y pes of l i st ener s al l ov er t he Sw i ng A PI.

A little life-changing application


Ok ay , our appl i c at i on i s pr et t y si mpl e. You’v e got a b ut t on t hat
say s, “Shoul d I do i t ?” and w hen y ou c l i c k on t hat b ut t on t he
l i st ener s (ob ser v er s) get t o answ er t he quest i on i n any w ay t hey
w ant . W e’r e i mpl ement i ng t w o suc h l i st ener s, c al l ed t he
A ngel Li st ener and t he Dev i l Li st ener . Her e’s how t he appl i c at i on
b ehav es:

Coding the life-changing application


Thi s l i f e-c hangi ng appl i c at i on r equi r es v er y l i t t l e c ode. A l l w e
need t o do i s c r eat e a JBut t on ob jec t , add i t t o a JFr ame, and set up
our l i st ener s. W e’r e goi ng t o use i nner c l asses f or t he l i st ener s,
w hi c h i s a c ommon t ec hni que i n Sw i ng pr ogr ammi ng. If y ou ar en’t
up on i nner c l asses or Sw i ng, y ou mi ght w ant t o r ev i ew t he Sw i ng
c hapt er i n y our f av or i t e Jav a r ef er enc e gui de.
SER IO U S C O D IN G
How about taking your use of the Observer Pattern even further? By using a
lambda expression rather than an inner class, you can skip the step of
creating an ActionListener object. With a lambda expression, we create a
function object instead, and the function object is the observer. And, when
you pass that function object to addActionListener(), Java ensures its
signature matches actionPerformed(), the one method in the
ActionListener interface.

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.

Let’s take a look at how you’d use lambda expressions as observers to


simplify our previous code:

The updated code, using lambda expressions:

N OT E
For more on lambda expressions, check out the Java docs.

there are no Dumb Questions


Q: I thought Jav a had Observ er and Observ able classes?

A: Good c at c h. Jav a used t o pr ov i de an Ob ser v ab l e c l ass (t he


Sub jec t ) and an Ob ser v er i nt er f ac e, w hi c h y ou c oul d use t o hel p
i nt egr at e t he Ob ser v er Pat t er n i n y our c ode. The Ob ser v ab l e c l ass
pr ov i ded met hods t o add, del et e, and not i f y ob ser v er s, so t hat y ou
di dn’t hav e t o w r i t e t hat c ode. A nd t he Ob ser v er i nt er f ac e pr ov i ded
an i nt er f ac e just l i k e our s, w i t h one updat e() met hod. These c l asses
w er e depr ec at ed i n Jav a 9. Fol k s f i nd i t easi er t o suppor t t he b asi c
Ob ser v er Pat t er n i n t hei r ow n c ode, or w ant somet hi ng mor e
r ob ust , so t he Ob ser v er /Ob ser v ab l e c l asses ar e b ei ng phased out .

Q: Does Jav a offer other built-in support for Observ er to replace


those classes?

A: Jav aBeans of f er s b ui l t -i n suppor t t hr ough


Pr oper t y ChangeEv ent s t hat ar e gener at ed w hen a Bean c hanges a
par t i c ul ar k i nd of pr oper t y , and sends not i f i c at i ons t o
Pr oper t y ChangeLi st ener s. Ther e ar e al so r el at ed
pub l i sher /sub sc r i b er c omponent s i n t he Fl ow A PI f or handl i ng
asy nc hr onous st r eams.

Q: Should I expect notifications from a Subj ect to its Observ ers


to arriv e in a specific order?

A: W i t h Jav a’s i mpl ement at i ons of Ob ser v er , t he JDK dev el oper s


spec i f i c al l y adv i se y ou t o not depend on any spec i f i c not i f i c at i on
or der .

That’s a good idea.


In our c ur r ent W eat her St at i on desi gn, w e ar e pus h ing al l t hr ee
pi ec es of dat a t o t he updat e() met hod i n t he di spl ay s, ev en i f t he
di spl ay s don’t need al l t hese v al ues. That ’s ok ay , b ut w hat i f
W eat her -O-Rama adds anot her dat a v al ue l at er , l i k e w i nd speed?
Then w e’l l hav e t o c hange al l t he updat e() met hods i n al l t he
di spl ay s, ev en i f most of t hem don’t need or w ant t he w i nd speed
dat a.

N ow , w het her w e pul l or push t he dat a t o t he Ob ser v er i s an


i mpl ement at i on det ai l , b ut i n a l ot of c ases i t mak es sense t o l et
Ob ser v er s r et r i ev e t he dat a t hey need r at her t han passi ng mor e
and mor e dat a t o t hem t hr ough t he updat e() met hod. A f t er al l , ov er
t i me, t hi s i s an ar ea t hat may c hange and gr ow unw i el dy . A nd, w e
k now CEO Johnny Hur r i c ane i s goi ng t o w ant t o ex pand t he
W eat her St at i on and sel l mor e di spl ay s, so l et ’s t ak e anot her pass at
t he desi gn and see i f w e c an mak e i t ev en easi er t o ex pand i n t he
f ut ur e.

U pdat i ng t he W eat her St at i on c ode t o al l ow Ob ser v er s t o pull t he


dat a t hey need i s a pr et t y st r ai ght f or w ar d ex er c i se. A l l w e need t o
do i s mak e sur e t he Sub jec t has get t er met hods f or i t s dat a, and t hen
c hange our Ob ser v er s t o use t hem t o pul l t he dat a t hat ’s
appr opr i at e f or t hei r needs. Let ’s do t hat .

Meanwhile, back at Weather-O-Rama

Ther e’s anot her w ay of handl i ng t he dat a i n t he Sub jec t : w e c an


r el y on t he Ob ser v er s t o pul l i t f r om t he Sub jec t as needed. Ri ght
now , w hen t he Sub jec t ’s dat a c hanges, w e pus h t he new v al ues f or
t emper at ur e, humi di t y , and pr essur e t o t he Ob ser v er s, b y passi ng
t hat dat a i n t he c al l t o updat e().

Let ’s set t hi ngs up so t hat w hen an Ob ser v er i s not i f i ed of a c hange,


i t c al l s get t er met hods on t he Sub jec t t o pull t he v al ues i t needs.

To sw i t c h t o usi ng pul l , w e need t o mak e a f ew smal l c hanges t o our


ex i st i ng c ode.

For the Subject to send notifications...

1 . W e’l l modi f y t he not i f y Ob ser v er s() met hod i n


W eat her Dat a t o c al l t he met hod updat e() i n t he Ob ser v er s
w i t h no ar gument s:

public void notifyObservers() {


for (Observer observer : observers) {
observer.update();
}
}

For an Observer to receive notifications...

1 . Then w e’l l modi f y t he Ob ser v er i nt er f ac e, c hangi ng t he


si gnat ur e of t he updat e() met hod so t hat i t has no
par amet er s:

public interface Observer {


public void update();
}

2. A nd f i nal l y , w e modi f y eac h c onc r et e Ob ser v er t o c hange


t he si gnat ur e of i t s r espec t i v e updat e() met hds and get t he
w eat her dat a f r om t he Sub jec t usi ng t he W eat her Dat a’s
get t er met hods. Her e’s t he new c ode f or t he
Cur r ent Condi t i onsDi spl ay c l ass:

Code Magnets

The For ec ast Di spl ay c l ass i s al l sc r amb l ed up on t he f r i dge. Can


y ou r ec onst r uc t t he c ode sni ppet s t o mak e i t w or k ? 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!

Test Drive the new code

Ok ay , y ou’v e got one mor e di spl ay t o updat e, t he A v g/Mi n/Max


di spl ay . Go ahead and do t hat now !

Just t o b e sur e, l et ’s r un t he new c ode...

Tools for your Design Toolbox


W el c ome t o t he end of Chapt er 2. You’v e added a f ew new t hi ngs t o
y our OO t ool b ox ...

B U L L ET PO IN T S

T he Observer Pattern defines a one-to-many relationship


between objects.

Subjects update Observers using a common interface.

Observers of any concrete type can participate in the pattern as


long as they implement the Observer interface.

Observers are loosely coupled in that the Subject knows nothing


about them, other than that they implement the Observer
interface.

You can push or pull data from the Subject when using the
pattern (pull is considered more “correct”).

Swing makes heavy use of the Observer Pattern, as do many


GUI frameworks.

You’ll also find the pattern in many other places, including


RxJava, JavaBeans, and RMI, as well as in other language
frameworks, like Cocoa, Swift, and JavaScript events.

T he Observer Pattern is related to the Publish/Subscribe


Pattern, which is for more complex situations with multiple
Subjects and/or multiple message types.

T he Observer Pattern is a commonly used pattern, and we’ll see


it again when we learn about Model-View-Controller.

Design Principle Challenge


For eac h desi gn pr i nc i pl e, desc r i b e how t he Ob ser v er Pat t er n
mak es use of t he pr i nc i pl e.

Design Patterns Crossword


Ti me t o gi v e y our r i ght b r ai n somet hi ng t o do agai n! A l l of t he
sol ut i on w or ds ar e f r om Chapt er 1 & Chapt er 2.

ACROSS

1 . One Sub jec t l i k es t o t al k t o _______ ob ser v er s.

3. Sub jec t i ni t i al l y w ant ed t o _________ al l t he dat a t o Ob ser v er .

6. CEO al most f or got t he ________ i ndex di spl ay .

8. Cur r ent Condi t i onsDi spl ay i mpl ement s t hi s i nt er f ac e.

9. Jav a f r amew or k w i t h l ot s of Ob ser v er s.

1 1 . A Sub jec t i s si mi l ar t o a __________.

1 2. Ob ser v er s l i k e t o b e ___________ w hen somet hi ng new


happens.

1 5. How t o get y our sel f of f t he Ob ser v er l i st .

1 6. Lor i w as b ot h an Ob ser v er and a _________.

1 8. Sub jec t i s an ______.

20. You w ant t o k eep y our c oupl i ng ________.

21 . Pr ogr am t o an __________ not an i mpl ement at i on.

22. Dev i l and A ngel ar e _________ t o t he b ut t on.

DOWN

1 . He di dn’t w ant any mor e i nt s, so he r emov ed hi msel f .

2. Temper at ur e, humi di t y , and __________.

4. W eat her -O-Rama’s CEO i s named af t er t hi s k i nd of st or m.

5. He say s y ou shoul d go f or i t .

7 . The Sub jec t doesn’t hav e t o k now muc h ab out t he _____.

1 0. The W eat her Dat a c l ass __________ t he Sub jec t i nt er f ac e.

1 3. Don’t c ount on t hi s f or not i f i c at i on.

1 4. Ob ser v er s ar e______ on t he Sub jec t .

1 7 . Impl ement t hi s met hod t o get not i f i ed.

1 9. Ji l l got one of her ow n.

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.)

A. We are coding to concrete implementations, not interfaces.

B. For every new display element, we need to alter code.

C. We have no way to add display elements at runtime.

D. T he display elements don’t implement a common interface.

E. We haven’t encapsulated what changes.

F. We are violating encapsulation of the WeatherData class.

Design Principle Challenge Solution


Code Magnets Solution

The For ec ast Di spl ay c l ass i s al l sc r amb l ed up on t he f r i dge. Can


y ou r ec onst r uc t t he c ode sni ppet s t o mak e i t w or k ? 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! Her e’s our sol ut i on.

Design Patterns Crossword Solution


Chapter 3. Decorating Objects: The
Decorator Pattern

Just call this chapter “Design Ey e for the I nheritance Guy .”


W e’l l r e-ex ami ne t he t y pi c al ov er use of i nher i t anc e and y ou’l l
l ear n how t o dec or at e y our c l asses at r unt i me usi ng a f or m of ob jec t
c omposi t i on. W hy ? Onc e y ou k now t he t ec hni ques of dec or at i ng,
y ou’l l b e ab l e t o gi v e y our (or someone el se’s) ob jec t s new
r esponsi b i l i t i es w ith out m ak ing any c ode c h anges to th e
underly ing c las s es .

Welcome to Starbuzz Coffee


St ar b uzz Cof f ee has made a name f or i t sel f as t he f ast est -gr ow i ng
c of f ee shop ar ound. If y ou’v e seen one on y our l oc al c or ner , l ook
ac r oss t he st r eet ; y ou’l l see anot her one.

Bec ause t hey ’v e gr ow n so qui c k l y , t hey ’r e sc r amb l i ng t o updat e


t hei r or der i ng sy st ems t o mat c h t hei r b ev er age of f er i ngs.

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...

In addi t i on t o y our c of f ee, y ou c an al so ask f or sev er al c ondi ment s


l i k e st eamed mi l k , soy , and moc ha (ot her w i se k now n as c hoc ol at e),
and hav e i t al l t opped of f w i t h w hi pped mi l k . St ar b uzz c har ges a
b i t f or eac h c ondi ment , so t hey r eal l y need t o get t hem b ui l t i nt o
t hei r or der sy st em.

Her e’s t hei r f i r st at t empt ...


B R AIN PO W ER
It’s pretty obvious that Starbuzz has created a maintenance nightmare for
themselves. What happens when the price of milk goes up? What do they
do when they add a new caramel topping?

T hinking beyond the maintenance problem, which of the design principles


that we’ve covered so far are they violating?

Hint: they’re violating tw o of them in a big w ay!

W el l , l et ’s gi v e i t a t r y . Let ’s st ar t w i t h t he Bev er age b ase c l ass and


add i nst anc e v ar i ab l es t o r epr esent w het her or not eac h b ev er age
has mi l k , soy , moc ha, and w hi p...

N ow l et ’s add i n t he sub c l asses, one f or eac h b ev er age on t he menu:


SH AR PEN YO U R PEN C IL
Write the cost() methods for the following classes (pseudo-Java is okay):

public class Beverage {


public double cost() {

}
}
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 and Student...

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?

Student: Guru, I have learned there are w ays of “inheriting” behavior at


runtime through composition and delegation.

Guru: Please, go on...

Student: When I inherit behavior by subclassing, that behavior is set


statically at compile time. In addition, all subclasses must inherit the same
behavior. If, how ever, I can extend an object’s behavior through
composition, then I can do this dynamically at runtime.

Guru: Very good; you are beginning to see the pow er of composition.

Student: Yes, it is possible for me to add multiple new responsibilities to


objects through this technique, including responsibilities that w ere not
even thought of by the designer of the superclass. And I don’t have to
touch their code!

Guru: What have you learned about the effect of composition on


maintaining your code?

Student: Well, that is w hat I w as getting at. By dynamically composing


objects, I can add new functionality by w riting new code rather than
altering existing code. Because I’m not changing existing code, the
chances of introducing bugs or causing unintended side effects in pre-
existing code are much reduced.

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.

The Open-Closed Principle


We’re on to one of the most important design principles:

Come on i n; w e’r e open. Feel f r ee t o ex t end our c l asses w i t h any


new b ehav i or y ou l i k e. If y our needs or r equi r ement s c hange (and
w e k now t hey w i l l ), just go ahead and mak e y our ow n ex t ensi ons.

Sor r y , w e’r e c los ed. That ’s r i ght , w e spent a l ot of t i me get t i ng t hi s


c ode c or r ec t and b ug f r ee, so w e c an’t l et y ou al t er t he ex i st i ng
c ode. It must r emai n c l osed t o modi f i c at i on. If y ou don’t l i k e i t , y ou
c an speak t o t he manager .
Our goal is to allow classes to be easily extended to incorporate
new behav ior without modify ing existing code. What do we get
if we accomplish this? Designs that are resilient to change and
flexible enough to take on new functionality to meet changing
requirements.

there are no Dumb Questions


Q: Open for extension and closed for modification? That sounds
v ery contradictory . How can a design be both?

A: That ’s a v er y good quest i on. It c er t ai nl y sounds c ont r adi c t or y at


f i r st . A f t er al l , t he l ess modi f i ab l e somet hi ng i s, t he har der i t i s t o
ex t end, r i ght ?

A s i t t ur ns out , t hough, t her e ar e some c l ev er OO t ec hni ques f or


al l ow i ng sy st ems t o b e ex t ended, ev en i f w e c an’t c hange t he
under l y i ng c ode. Thi nk ab out t he Ob ser v er Pat t er n (i n
Chapt er 2)...b y addi ng new Ob ser v er s, w e c an ex t end t he Sub jec t at
any t i me, w i t hout addi ng c ode t o t he Sub jec t . You’l l see qui t e a f ew
mor e w ay s of ex t endi ng b ehav i or w i t h ot her OO desi gn t ec hni ques.

Q: Okay , I understand Observ er, but how do I generally design


something to be extensible y et closed for modification?

A: Many of t he pat t er ns gi v e us t i me-t est ed desi gns t hat pr ot ec t


y our c ode f r om b ei ng modi f i ed b y suppl y i ng a means of ex t ensi on.
In t hi s c hapt er y ou’l l see a good ex ampl e of usi ng t he Dec or at or
Pat t er n t o f ol l ow t he Open-Cl osed Pr i nc i pl e.

Q: How can I make ev ery part of my design follow the Open-


Closed Principle?

A: U sual l y , y ou c an’t . Mak i ng OO desi gn f l ex i b l e and open t o


ex t ensi on w i t hout modi f y i ng ex i st i ng c ode t ak es t i me and ef f or t . In
gener al , w e don’t hav e t he l ux ur y of t y i ng dow n ev er y par t of our
desi gns (and i t w oul d pr ob ab l y b e w ast ef ul ). Fol l ow i ng t he Open-
Cl osed Pr i nc i pl e usual l y i nt r oduc es new l ev el s of ab st r ac t i on,
w hi c h adds c ompl ex i t y t o our c ode. You w ant t o c onc ent r at e on
t hose ar eas t hat ar e most l i k el y t o c hange i n y our desi gns and appl y
t he pr i nc i pl es t her e.

Q: How do I know which areas of change are more important?

A: That i s par t l y a mat t er of ex per i enc e i n desi gni ng OO sy st ems


and al so a mat t er of k now i ng t he domai n y ou ar e w or k i ng i n.
Look i ng at ot her ex ampl es w i l l hel p y ou l ear n t o i dent i f y ar eas of
c hange i n y our ow n desi gns.

W h ile it m a y s e e m lik e a co ntra d ictio n, th e re a re


te ch niq ue s fo r a llo w ing co d e to b e e xte nd e d w ith o ut
d ire ct m o d ifica tio n.

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 .

Meet the Decorator Pattern


Ok ay , w e’v e seen t hat r epr esent i ng our b ev er age and c ondi ment s
w i t h i nher i t anc e has not w or k ed out v er y w el l —w e get c l ass
ex pl osi ons and r i gi d desi gns, or w e add f unc t i onal i t y t o t he b ase
c l ass t hat i sn’t appr opr i at e f or some of t he sub c l asses.

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.

2. Decorate it with a Mocha obj ect.

3. Decorate it with a Whip obj ect.

4. Call the cost() method and rely on delegation to add up


the condiment costs.

Ok ay , b ut how do y ou “dec or at e” an ob jec t , and how does del egat i on


c ome i nt o t hi s? A hi nt : t hi nk of dec or at or ob jec t s as “w r apper s.”
Let ’s see how t hi s w or k s...

Constructing a drink order with Decorators

1 . We start with our DarkRoast obj ect.

2. The customer wants Mocha, so we create a Mocha


obj ect and wrap it around the DarkRoast.

3. The customer also wants Whip, so we create a Whip


decorator and wrap Mocha with it.
N O TE
So, a DarkRoast wrapped in Mocha and Whip is still
a Beverage and we can do anything with it we can
do with a DarkRoast, including call its cost()
method.

4. Now it’s time to compute the cost for the customer. We


do this by calling cost() on the outermost decorator,
Whip, and Whip is going to delegate computing the
cost to the obj ects it decorates. And so on. Let’s see
how this works:

Okay, here’s what we know about Decorators, so far...

Dec or at or s hav e t he same super t y pe as t he ob jec t s t hey


dec or at e.

You c an use one or mor e dec or at or s t o w r ap an ob jec t .

Gi v en t hat t he dec or at or has t he same super t y pe as t he


ob jec t i t dec or at es, w e c an pass ar ound a dec or at ed ob jec t
i n pl ac e of t he or i gi nal (w r apped) ob jec t .

The dec or at or adds i t s ow n b ehav i or b ef or e and/or af t er


del egat i ng t o t he ob jec t i t dec or at es t o do t he r est of t he
job .

N O TE
Key point!

Ob jec t s c an b e dec or at ed at any t i me, so w e c an dec or at e


ob jec t s dy nami c al l y at r unt i me w i t h as many dec or at or s
as w e l i k e.

No w le t’s s e e h o w th is a ll re a lly w o rk s b y lo o k ing a t


th e De co ra to r Pa tte rn d e finitio n a nd w riting s o m e
co d e .

The Decorator Pattern defined


Let ’s f i r st t ak e a l ook at t he Dec or at or Pat t er n desc r i pt i on:

N O TE
The Decorator Pattern attaches additional responsibilities to
an object dynamically. Decorators provide a flexible alternative
to subclassing for extending functionality.

W hi l e t hat desc r i b es t he role of t he Dec or at or Pat t er n, i t doesn’t


gi v e us a l ot of i nsi ght i nt o how w e’d apply t he pat t er n t o our ow n
i mpl ement at i on. Let ’s t ak e a l ook at t he c l ass di agr am, w hi c h i s a
l i t t l e mor e r ev eal i ng (on t he nex t page w e’l l l ook at t he same
st r uc t ur e appl i ed t o t he b ev er age pr ob l em).
Decorating our Beverages
Let’s rework our Starbuzz bev erages using the Decorator
Pattern...

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: W hat do y ou mean?

Mary : Look at t he c l ass di agr am. The Condi ment Dec or at or i s


ex t endi ng t he Bev er age c l ass. That ’s i nher i t anc e, r i ght ?

Sue: Tr ue. I t hi nk t he poi nt i s t hat i t ’s v i t al t hat t he dec or at or s


hav e t he same t y pe as t he ob jec t s t hey ar e goi ng t o dec or at e. So her e
w e’r e usi ng i nher i t anc e t o ac hi ev e t he ty pe m atc h ing, b ut w e
ar en’t usi ng i nher i t anc e t o get beh av ior.

Mary : Ok ay , I c an see how dec or at or s need t he same “i nt er f ac e” as


t he c omponent s t hey w r ap b ec ause t hey need t o st and i n pl ac e of
t he c omponent . But w her e does t he b ehav i or c ome i n?

Sue: W hen w e c ompose a dec or at or w i t h a c omponent , w e ar e


addi ng new b ehav i or . W e ar e ac qui r i ng new b ehav i or not b y
inh eriting i t f r om a super c l ass, b ut b y c om pos ing ob jec t s t oget her .

Mary : Ok ay , so w e’r e sub c l assi ng t he ab st r ac t c l ass Bev er age i n


or der t o hav e t he c or r ec t t y pe, not t o i nher i t i t s b ehav i or . The
b ehav i or c omes i n t hr ough t he c omposi t i on of dec or at or s w i t h t he
b ase c omponent s as w el l as ot her dec or at or s.

Sue: That ’s r i ght .

Mary : Oh, I get i t ! A nd b ec ause w e ar e usi ng ob jec t c omposi t i on, w e


get a w hol e l ot mor e f l ex i b i l i t y ab out how t o mi x and mat c h
c ondi ment s and b ev er ages. V er y sl i c k .

Sue: Yes, i f w e r el y on i nher i t anc e, t hen our b ehav i or c an onl y b e


det er mi ned st at i c al l y at c ompi l e t i me. In ot her w or ds, w e get onl y
w hat ev er b ehav i or t he super c l ass gi v es us or t hat w e ov er r i de.
W i t h c omposi t i on, w e c an mi x and mat c h dec or at or s any w ay w e
l i k e...at runtim e.

Mary : I get i t —w e c an i mpl ement new dec or at or s at any t i me t o add


new b ehav i or . If w e r el i ed on i nher i t anc e, w e’d hav e t o go i n and
c hange ex i st i ng c ode any t i me w e w ant ed new b ehav i or .

Sue: Ex ac t l y .

Mary : I just hav e one mor e quest i on: i f al l w e need t o i nher i t i s t he


t y pe of t he c omponent , how c ome w e di dn’t use an i nt er f ac e i nst ead
of an ab st r ac t c l ass f or t he Bev er age c l ass?

Sue: W el l , r ememb er , w hen w e got t hi s c ode, St ar b uzz al r eady h ad


an ab st r ac t Bev er age c l ass. Tr adi t i onal l y t he Dec or at or Pat t er n
does spec i f y an ab st r ac t c omponent , b ut i n Jav a, ob v i ousl y , w e
c oul d use an i nt er f ac e. But w e al w ay s t r y t o av oi d al t er i ng ex i st i ng
c ode, so don’t “f i x ” i t i f t he ab st r ac t c l ass w i l l w or k just f i ne.

New barista training


Mak e a pi c t ur e f or w hat happens w hen t he or der i s f or a “doub l e
moc ha soy l at t e w i t h w hi p” b ev er age. U se t he menu t o get t he
c or r ec t pr i c es, and dr aw y our pi c t ur e usi ng t he same f or mat w e
used ear l i er (f r om a f ew pages b ac k ):

SH AR PEN YO U R PEN C IL
Draw your picture here.
Writing the Starbuzz code

I t’s time to whip this design into some real 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:

Bev erage is simple enough. Let’s implement the abstract class


for the Condiments (the Decorator) as well:

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.

Serving some coffees


Congr at ul at i ons. It ’s t i me t o si t b ac k , or der a f ew c of f ees, and
mar v el at t he f l ex i b l e desi gn y ou c r eat ed w i t h t he Dec or at or
Pat t er n.

Here’s some test code* to make orders:

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.

Now, let’s get those orders in:

there are no Dumb Questions


Q: I ’m a little worried about code that might test for a specific
concrete component—say , HouseBlend—and do something, like
issue a discount. Once I ’v e wrapped the HouseBlend with
decorators, this isn’t going to work any more.

A: That i s ex ac t l y r i ght . If y ou hav e c ode t hat r el i es on t he c onc r et e


c omponent ’s t y pe, dec or at or s w i l l b r eak t hat c ode. A s l ong as y ou
onl y w r i t e c ode agai nst t he ab st r ac t c omponent t y pe, t he use of
dec or at or s w i l l r emai n t r anspar ent t o y our c ode. How ev er , onc e
y ou st ar t w r i t i ng c ode agai nst c onc r et e c omponent s, y ou’l l w ant t o
r et hi nk y our appl i c at i on desi gn and y our use of dec or at or s.

Q: Wouldn’t it be easy for some client of a bev erage to end up


with a decorator that isn’t the outermost decorator? Like if I had
a DarkRoast with Mocha, Soy , and Whip, it would be easy to
write code that somehow ended up with a reference to Soy
instead of Whip, which means it would not include Whip in the
order.

A: You c oul d c er t ai nl y ar gue t hat y ou hav e t o manage mor e ob jec t s


w i t h t he Dec or at or Pat t er n and so t her e i s an i nc r eased c hanc e t hat
c odi ng er r or s w i l l i nt r oduc e t he k i nds of pr ob l ems y ou suggest .
How ev er , w e t y pi c al l y c r eat e dec or at or s b y usi ng ot her pat t er ns
l i k e Fac t or y and Bui l der . Onc e w e’v e c ov er ed t hese pat t er ns, y ou’l l
see t hat t he c r eat i on of t he c onc r et e c omponent w i t h i t s dec or at or
i s “w el l enc apsul at ed” and doesn’t l ead t o t hese k i nds of pr ob l ems.

Q: Can decorators know about the other decorations in the


chain? Say I wanted my getDescription() method to print
“Whip, Double Mocha” instead of “Mocha, Whip, Mocha.” That
would require that my outermost decorator know all the
decorators it is wrapping.

A: Dec or at or s ar e meant t o add b ehav i or t o t he ob jec t t hey w r ap.


W hen y ou need t o peek at mul t i pl e l ay er s i nt o t he dec or at or c hai n,
y ou ar e st ar t i ng t o push t he dec or at or b ey ond i t s t r ue i nt ent .
N ev er t hel ess, suc h t hi ngs ar e possi b l e. Imagi ne a
Condi ment Pr et t y Pr i nt dec or at or t hat par ses t he f i nal dec r i pt i on
and c an pr i nt “Moc ha, W hi p, Moc ha” as “W hi p, Doub l e Moc ha.” N ot e
t hat get Desc r i pt i on() c oul d r et ur n an A r r ay Li st of desc r i pt i ons t o
mak e t hi s easi er .

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?

public abstract class Beverage {


public enum Size { TALL, GRANDE, VENTI };
Size size = Size.TALL;
String description = “Unknown Beverage”;
public String getDescription() {
return description;
}
public void setSize(Size size) {
this.size = size;
}
public Size getSize() {
return this.size;
}
public abstract double cost();
}

Real-World Decorators: Java I/O


The l ar ge numb er of c l asses i n t he jav a.i o pac k age
i s...ov erw h elm ing. Don’t f eel al one i f y ou sai d “w hoa” t he f i r st (and
sec ond and t hi r d) t i me y ou l ook ed at t hi s A PI. But now t hat y ou
k now t he Dec or at or Pat t er n, t he I/O c l asses shoul d mak e mor e sense
si nc e t he jav a.i o pac k age i s l ar gel y b ased on Dec or at or . Her e’s a
t y pi c al set of ob jec t s t hat use dec or at or s t o add f unc t i onal i t y t o
r eadi ng dat a f r om a f i l e:

Decorating the java.io classes


Buf f er edInput St r eam and Zi pInput St r eam b ot h ex t end
Fi l t er Input St r eam, w hi c h ex t ends Input St r eam. Input St r eam ac t s
as t he ab st r ac t dec or at or c l ass:
You c an see t hat t hi s i sn’t so di f f er ent f r om t he St ar b uzz desi gn. You
shoul d now b e i n a good posi t i on t o l ook ov er t he jav a.i o A PI doc s
and c ompose dec or at or s on t he v ar i ous input st r eams.

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).

Jav a I/O al so poi nt s out one of t he dow ns ides of t he Dec or at or


Pat t er n: desi gns usi ng t hi s pat t er n of t en r esul t i n a l ar ge numb er
of smal l c l asses t hat c an b e ov er w hel mi ng t o a dev el oper t r y i ng t o
use t he Dec or at or -b ased A PI. But now t hat y ou k now how Dec or at or
w or k s, y ou c an k eep t hi ngs i n per spec t i v e and w hen y ou’r e usi ng
someone el se’s Dec or at or -heav y A PI, y ou c an w or k t hr ough how
t hei r c l asses ar e or gani zed so t hat y ou c an easi l y use w r appi ng t o
get t he b ehav i or y ou’r e af t er .

Writing your own Java I/O Decorator


Ok ay , y ou k now t he Dec or at or Pat t er n, and y ou’v e seen t he I/O
c l ass di agr am. You shoul d b e r eady t o w r i t e y our ow n i nput
dec or at or .

How ab out t hi s: w r i t e a dec or at or t hat c onv er t s al l upper c ase


c har ac t er s t o l ow er c ase i n t he i nput st r eam. In ot her w or ds, i f w e
r ead i n “I k now t he Dec or at or Pat t er n t her ef or e I RU LE!” t hen y our
dec or at or c onv er t s t hi s t o “i k now t he dec or at or pat t er n t her ef or e
i r ul e!”
N O TE
REMEMBER: we don’t provide import and package statements
in the code listings. Get the complete source code from
https://wickedlysmart.com/head-first-design-patterns.

Test out your new Java I/O Decorator


W r i t e some qui c k c ode t o t est t he I/O dec or at or :

Giv e it a spin:

PAT T ER N S EXPO SED


This week’s interview: Confessions of a Decorator

Head First: Welcome, Decorator Pattern. We’ve heard that you’ve been a
bit down on yourself lately?

Decorator: Yes, I know the world sees me as the glamorous design


pattern, but you know, I’ve got my share of problems just like everyone.

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.

HeadFirst: Can you give us an example?

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.

HeadFirst: Well, I think everyone understands that you have to be careful


when inserting decorators. I don’t think this is a reason to be too down on
yourself.

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?

Decorator: T hat’s true; I should talk to those guys more often.

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!

Decorator: I’ll do my best, thank you.

Tools for your Design Toolbox


You’v e got anot her c hapt er under y our b el t and a new pr i nc i pl e
and pat t er n i n t he t ool b ox .
B U L L ET PO IN T S

Inheritance is one form of extension, but not necessarily the


best way to achieve flexibility in our designs.

In our designs we should allow behavior to be extended without


the need to modify existing code.

Composition and delegation can often be used to add new


behaviors at runtime.

T he Decorator Pattern provides an alternative to subclassing for


extending behavior.

T he Decorator Pattern involves a set of decorator classes that


are used to wrap concrete components.

Decorator classes mirror the type of the components they


decorate. (In fact, they are the same type as the components
they decorate, either through inheritance or interface
implementation.)

Decorators change the behavior of their components by adding


new functionality before and/or after (or even in place of) method
calls to the component.

You can wrap a component with any number of decorators.

Decorators are typically transparent to the client of the


component—that is, unless the client is relying on the
component’s concrete type.

Decorators can result in many small objects in our design, and


overuse can be complex.

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 class Beverage {

// declare instance variables for milkCost,


// soyCost, mochaCost, and whipCost, and
// getters and setters for milk, soy, mocha
// and whip.

public double cost() {

double condimentCost = 0.0;


if (hasMilk()) {
condimentCost += milkCost;
}
if (hasSoy()) {
condimentCost += soyCost;
}
if (hasMocha()) {
condimentCost += mochaCost;
}
if (hasWhip()) {
condimentCost += whipCost;
}
return condimentCost;
}
}

public class DarkRoast extends Beverage {

public DarkRoast() {
description = “Most Excellent Dark Roast”;
}

public double cost() {


return 1.99 + super.cost();
}
}
SH AR PEN YO U R PEN C IL
SO L U T IO N
New barista training

“double mocha soy latte with whip”

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

Get ready to bake some loosely coupled OO designs. Ther e i s


mor e t o mak i ng ob jec t s t han just usi ng t he new oper at or . You’l l
l ear n t hat i nst ant i at i on i s an ac t i v i t y t hat shoul dn’t al w ay s b e
done i n pub l i c and c an of t en l ead t o c oupling problem s . A nd w e
don’t w ant th at, do w e? Fi nd out how Fac t or y Pat t er ns c an hel p sav e
y ou f r om emb ar r assi ng dependenc i es.

When y ou see “new,” think “concrete.”

Yes, w hen y ou use t he new oper at or y ou ar e c er t ai nl y


i nst ant i at i ng a c onc r et e c l ass, so t hat ’s def i ni t el y an
i mpl ement at i on and not an i nt er f ac e. A nd y ou mak e a good
ob ser v at i on: t hat t y i ng y our c ode t o a c onc r et e c l ass c an mak e i t
mor e f r agi l e and l ess f l ex i b l e.

W hen w e hav e a w hol e set of r el at ed c onc r et e c l asses, of t en w e end


up w r i t i ng c ode l i k e t hi s:
Her e w e’v e got sev er al c onc r et e c l asses b ei ng i nst ant i at ed, and t he
dec i si on of w hi c h t o i nst ant i at e i s made at r unt i me dependi ng on
some set of c ondi t i ons.

W hen y ou see c ode l i k e t hi s, y ou k now t hat w hen i t c omes t i me f or


c hanges or ex t ensi ons, y ou’l l hav e t o r eopen t hi s c ode and ex ami ne
w hat needs t o b e added (or del et ed). Of t en t hi s k i nd of c ode ends up
i n sev er al par t s of t he appl i c at i on, mak i ng mai nt enanc e and
updat es mor e di f f i c ul t and er r or -pr one.

What’s wrong with “new”?

Tec hni c al l y t her e’s not hi ng w r ong w i t h t he new oper at or . A f t er


al l , i t ’s a f undament al par t of most moder n ob jec t -or i ent ed
l anguages. The r eal c ul pr i t i s our ol d f r i end CHA N GE and how
c hange i mpac t s our use of new.

By c odi ng t o an i nt er f ac e, y ou k now y ou c an i nsul at e y our sel f f r om


many of t he c hanges t hat mi ght happen t o a sy st em dow n t he r oad.
W hy ? If y our c ode i s w r i t t en t o an i nt er f ac e, t hen i t w i l l w or k
w i t h any new c l asses i mpl ement i ng t hat i nt er f ac e t hr ough
pol y mor phi sm. How ev er , w hen y ou hav e c ode t hat mak es use of l ot s
of c onc r et e c l asses, y ou’r e l ook i ng f or t r oub l e b ec ause t hat c ode
may hav e t o b e c hanged as new c onc r et e c l asses ar e added. So, i n
ot her w or ds, y our c ode w i l l not b e “c l osed f or modi f i c at i on.” To
ex t end y our c ode w i t h new c onc r et e t y pes, y ou’l l hav e t o r eopen i t .

N O TE
Remember that designs should be “open for extension but
closed for modification.” See Chapter 3 for a review.

So w hat c an y ou do? It ’s t i mes l i k e t hese t hat y ou c an f al l b ac k on


OO desi gn pr i nc i pl es t o l ook f or c l ues. Rememb er , our f i r st
pr i nc i pl e deal s w i t h c hange and gui des us t o identify th e as pec ts
th at v ary and s eparate th em from w h at s tay s th e s am e.

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?

Identifying the aspects that vary


Let ’s say y ou hav e a pi zza shop, and as a c ut t i ng-edge pi zza st or e
ow ner i n Ob jec t v i l l e y ou mi ght end up w r i t i ng some c ode l i k e t hi s:
But y ou need more than one ty pe of pizza...

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:

But the pressure is on to add more pizza types


You r eal i ze t hat al l of y our c ompet i t or s hav e added a c oupl e of
t r endy pi zzas t o t hei r menus: t he Cl am Pi zza and t he V eggi e Pi zza.
Ob v i ousl y y ou need t o k eep up w i t h t he c ompet i t i on, so y ou’l l add
t hese i t ems t o y our menu. A nd y ou hav en’t b een sel l i ng many Gr eek
pi zzas l at el y , so y ou dec i de t o t ak e t hat of f t he menu:

Cl ear l y , deal i ng w i t h w h ic h c onc r et e c l ass i s i nst ant i at ed i s r eal l y


messi ng up our or der Pi zza() met hod and pr ev ent i ng i t f r om b ei ng
c l osed f or modi f i c at i on. But now t hat w e k now w hat i s v ar y i ng and
w hat i sn’t , i t ’s pr ob ab l y t i me t o enc apsul at e i t .

Encapsulating object creation


So now w e k now w e’d b e b et t er of f mov i ng t he ob jec t c r eat i on out
of t he or der Pi zza() met hod. But how ? W el l , w hat w e’r e goi ng t o do i s
t ak e t he c r eat i on c ode and mov e i t out i nt o anot her ob jec t t hat i s
onl y goi ng t o b e c onc er ned w i t h c r eat i ng pi zzas.
We’v e got a name for this new obj ect: we call it a F actory .

Fac t or i es handl e t he det ai l s of ob jec t c r eat i on. Onc e w e hav e a


Si mpl ePi zzaFac t or y , our or der Pi zza() met hod b ec omes a c l i ent of
t hat ob jec t . A ny t i me i t needs a pi zza, i t ask s t he pi zza f ac t or y t o
mak e one. Gone ar e t he day s w hen t he or der Pi zza() met hod needs t o
k now ab out Gr eek v er sus Cl am pi zzas. N ow t he or der Pi zza() met hod
just c ar es t hat i t get s a pi zza t hat i mpl ement s t he Pi zza i nt er f ac e so
t hat i t c an c al l pr epar e(), b ak e(), c ut (), and b ox ().

W e’v e st i l l got a f ew det ai l s t o f i l l i n her e; f or i nst anc e, w hat does


t he or der Pi zza() met hod r epl ac e i t s c r eat i on c ode w i t h? Let ’s
i mpl ement a si mpl e f ac t or y f or t he pi zza st or e and f i nd out ...

Building a simple pizza factory


W e’l l st ar t w i t h t he f ac t or y i t sel f . W hat w e’r e goi ng t o do i s def i ne
a c l ass t hat enc apsul at es t he ob jec t c r eat i on f or al l pi zzas. Her e i t
i s...

there are no Dumb Questions


Q: What’s the adv antage of this? I t looks like we’re j ust pushing
the problem off to another obj ect.

A: One t hi ng t o r ememb er i s t hat t he Si mpl ePi zzaFac t or y may hav e


many c l i ent s. W e’v e onl y seen t he or der Pi zza() met hod; how ev er ,
t her e may b e a Pi zzaShopMenu c l ass t hat uses t he f ac t or y t o get
pi zzas f or t hei r c ur r ent desc r i pt i on and pr i c e. W e mi ght al so hav e
a HomeDel i v er y c l ass t hat handl es pi zzas i n a di f f er ent w ay t han
our Pi zzaShop c l ass b ut i s al so a c l i ent of t he f ac t or y .

So, b y enc apsul at i ng t he pi zza c r eat i ng i n one c l ass, w e now hav e


onl y one pl ac e t o mak e modi f i c at i ons w hen t he i mpl ement at i on
c hanges.

A nd, don’t f or get , w e’r e al so just ab out t o r emov e t he c onc r et e


i nst ant i at i ons f r om our c l i ent c ode.

Q: I ’v e seen a similar design where a factory like this is defined


as a static method. What’s the difference?

A: Def i ni ng a si mpl e f ac t or y as a st at i c met hod i s a c ommon


t ec hni que and i s of t en c al l ed a st at i c f ac t or y . W hy use a st at i c
met hod? Bec ause y ou don’t need t o i nst ant i at e an ob jec t t o mak e use
of t he c r eat e met hod. But i t al so has t he di sadv ant age t hat y ou c an’t
sub c l ass and c hange t he b ehav i or of t he c r eat e met hod.

Reworking the PizzaStore class


N ow i t ’s t i me t o f i x up our c l i ent c ode. W hat w e w ant t o do i s r el y
on t he f ac t or y t o c r eat e t he pi zzas f or us. Her e ar e t he c hanges:
B R AIN PO W ER
We know that object composition allows us to change behavior
dynamically at runtime (among other things) because we can swap in and
out implementations. How might we be able to use that in the PizzaStore?
What factory implementations might we be able to swap in and out?

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).

The Simple Factory defined


The Si mpl e Fac t or y i sn’t ac t ual l y a Desi gn Pat t er n; i t ’s mor e of a
pr ogr ammi ng i di om. But i t i s c ommonl y used, so w e’l l gi v e i t a Head
Fi r st Pat t er n Honor ab l e Ment i on. Some dev el oper s do mi st ak e t hi s
i di om f or t he Fac t or y Pat t er n, b ut t he nex t t i me t hat happens y ou
c an sub t l y show y ou k now y our st uf f ; just don’t st r ut as y ou educ at e
t hem on t he di st i nc t i on.

Just b ec ause Si mpl e Fac t or y i sn’t a REA L pat t er n doesn’t mean w e


shoul dn’t c hec k out how i t ’s put t oget her . Let ’s t ak e a l ook at t he
c l ass di agr am of our new Pi zza St or e:

Thi nk of Si mpl e Fac t or y as a w ar m-up. N ex t , w e’l l ex pl or e t w o


heav y -dut y pat t er ns t hat ar e b ot h f ac t or i es. But don’t w or r y ,
t her e’s mor e pi zza t o c ome!

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.

Franchising the pizza store


Your Ob jec t v i l l e Pi zza St or e has done so w el l t hat y ou’v e t r ounc ed
t he c ompet i t i on and now ev er y one w ant s a Pi zza St or e i n t hei r ow n
nei ghb or hood. A s t he f r anc hi ser , y ou w ant t o ensur e t he qual i t y of
t he f r anc hi se oper at i ons and so y ou w ant t hem t o use y our t i me-
t est ed c ode.
But w hat ab out r egi onal di f f er enc es? Eac h f r anc hi se mi ght w ant t o
of f er di f f er ent st y l es of pi zzas (N ew Yor k , Chi c ago, and Cal i f or ni a,
t o name a f ew ), dependi ng on w her e t he f r anc hi se st or e i s l oc at ed
and t he t ast es of t he l oc al pi zza c onnoi sseur s.

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).

We’ve seen one approach...

If w e t ak e out Si mpl ePi zzaFac t or y and c r eat e t hr ee di f f er ent


f ac t or i es—N YPi zzaFac t or y , Chi c agoPi zzaFac t or y , and
Cal i f or ni aPi zzaFac t or y —t hen w e c an just c ompose t he Pi zzaSt or e
w i t h t he appr opr i at e f ac t or y and a f r anc hi se i s good t o go. That ’s
one appr oac h.

Let ’s see w hat t hat w oul d l ook l i k e...

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

So y ou t est -mar k et ed t he Si mpl eFac t or y i dea, and w hat y ou f ound


w as t hat t he f r anc hi ses w er e usi ng y our f ac t or y t o c r eat e pi zzas,
b ut st ar t i ng t o empl oy t hei r ow n home-gr ow n pr oc edur es f or t he
r est of t he pr oc ess: t hey ’d b ak e t hi ngs a l i t t l e di f f er ent l y , t hey ’d
f or get t o c ut t he pi zza, and t hey ’d use t hi r d-par t y b ox es.

Ret hi nk i ng t he pr ob l em a b i t , y ou see t hat w hat y ou’d r eal l y l i k e


t o do i s c r eat e a f r amew or k t hat t i es t he st or e and t he pi zza c r eat i on
t oget her , y et st i l l al l ow s t hi ngs t o r emai n f l ex i b l e.

In our ear l y c ode, b ef or e t he Si mpl ePi zzaFac t or y , w e had t he pi zza-


mak i ng c ode t i ed t o t he Pi zzaSt or e, b ut i t w asn’t f l ex i b l e. So, how
c an w e hav e our pi zza and eat i t t oo?

A framework for the pizza store


Ther e is a w ay t o l oc al i ze al l t he pi zza-mak i ng ac t i v i t i es t o t he
Pi zzaSt or e c l ass, and t o gi v e t he f r anc hi ses f r eedom t o hav e t hei r
ow n r egi onal st y l e.

W hat w e’r e goi ng t o do i s put t he c r eat ePi zza() met hod b ac k i nt o


Pi zzaSt or e, b ut t hi s t i me as an ab st r ac t met hod, and t hen c r eat e a
Pi zzaSt or e sub c l ass f or eac h r egi onal st y l e.

Fi r st , l et ’s l ook at t he c hanges t o t he Pi zzaSt or e:

N ow w e’v e got a st or e w ai t i ng f or sub c l asses; w e’r e goi ng t o hav e a


sub c l ass f or eac h r egi onal t y pe (N YPi zzaSt or e, Chi c agoPi zzaSt or e,
Cal i f or ni aPi zzaSt or e) and eac h sub c l ass i s goi ng t o mak e t he
dec i si on ab out w hat mak es up a pi zza. Let ’s t ak e a l ook at how t hi s i s
goi ng t o w or k .

Allowing the subclasses to decide


Rememb er , t he Pi zza St or e al r eady has a w el l -honed or der sy st em i n
t he or der Pi zza() met hod and y ou w ant t o ensur e t hat i t ’s c onsi st ent
ac r oss al l f r anc hi ses.

W hat v ar i es among t he r egi onal Pi zza St or es i s t he st y l e of pi zzas


t hey mak e—N ew Yor k pi zza has t hi n c r ust , Chi c ago pi zza has t hi c k ,
and so on—and w e ar e goi ng t o push al l t hese v ar i at i ons i nt o t he
c r eat ePi zza() met hod and mak e i t r esponsi b l e f or c r eat i ng t he r i ght
k i nd of pi zza. The w ay w e do t hi s i s b y l et t i ng eac h sub c l ass of Pi zza
St or e def i ne w hat t he c r eat ePi zza() met hod l ook s l i k e. So, w e’l l hav e
a numb er of c onc r et e sub c l asses of Pi zza St or e, eac h w i t h i t s ow n
pi zza v ar i at i ons, al l f i t t i ng w i t hi n t he Pi zza St or e f r amew or k and
st i l l mak i ng use of t he w el l -t uned or der Pi zza() met hod.

W el l , t hi nk ab out i t f r om t he poi nt of v i ew of t he Pi zzaSt or e’s


or der Pi zza() met hod: i t i s def i ned i n t he ab st r ac t Pi zzaSt or e, b ut
c onc r et e t y pes ar e onl y c r eat ed i n t he sub c l asses.

N ow , t o t ak e t hi s a l i t t l e f ur t her , t he or der Pi zza() met hod does a l ot


of t hi ngs w i t h a Pi zza ob jec t (l i k e pr epar e, b ak e, c ut , b ox ), b ut
b ec ause Pi zza i s ab st r ac t , or der Pi zza() has no i dea w hat r eal
c onc r et e c l asses ar e i nv ol v ed. In ot her w or ds, i t ’s dec oupl ed!

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.

So, i s t her e a r eal -t i me dec i si on t hat sub c l asses mak e? N o, b ut f r om


t he per spec t i v e of or der Pi zza(), i f y ou c hose a N YSt y l ePi zzaSt or e,
t hat sub c l ass get s t o det er mi ne w hi c h pi zza i s made. So t he
sub c l asses ar en’t r eal l y “dec i di ng”—i t w as y ou w ho dec i ded b y
c hoosi ng w hi c h st or e y ou w ant ed—b ut t hey do det er mi ne w hi c h
k i nd of pi zza get s made.

Let’s make a Pizza Store


Bei ng a f r anc hi se has i t s b enef i t s. You get al l t he Pi zzaSt or e
f unc t i onal i t y f or f r ee. A l l t he r egi onal st or es need t o do i s sub c l ass
Pi zzaSt or e and suppl y a c r eat ePi zza() met hod t hat i mpl ement s t hei r
st y l e of pi zza. W e’l l t ak e c ar e of t he b i g t hr ee pi zza st y l es f or t he
f r anc hi sees.

Her e’s t he N ew Yor k r egi onal st y l 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!

Onc e w e’v e got our Pi zzaSt or e sub c l asses b ui l t , i t w i l l b e t i me t o


see ab out or der i ng up a pi zza or t w o. But b ef or e w e do t hat , w hy
don’t y ou t ak e a c r ac k at b ui l di ng t he Chi c ago-st y l e and Cal i f or ni a-
st y l e pi zza st or es on t he nex t page?

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:

Declaring a factory method


W i t h just a c oupl e of t r ansf or mat i ons t o t he Pi zzaSt or e c l ass, w e’v e
gone f r om hav i ng an ob jec t handl e t he i nst ant i at i on of our
c onc r et e c l asses t o a set of sub c l asses t hat ar e now t ak i ng on t hat
r esponsi b i l i t y . Let ’s t ak e a c l oser l ook :

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

So how do they order?

1 . Fi r st , Joel and Et han need an i nst anc e of a Pi zzaSt or e. Joel


needs t o i nst ant i at e a Chi c agoPi zzaSt or e and Et han needs
a N YPi zzaSt or e.

2. W i t h a Pi zzaSt or e i n hand, b ot h Et han and Joel c al l t he


or der Pi zza() met hod and pass i n t he t y pe of pi zza t hey
w ant (c heese, v eggi e, and so on).

3. To c r eat e t he pi zzas, t he c r eat ePi zza() met hod i s c al l ed,


w hi c h i s def i ned i n t he t w o sub c l asses N YPi zzaSt or e and
Chi c agoPi zzaSt or e. A s w e def i ned t hem, t he N YPi zzaSt or e
i nst ant i at es a N Y-st y l e pi zza, and t he Chi c agoPi zzaSt or e
i nst ant i at es a Chi c ago-st y l e pi zza. In ei t her c ase, t he Pi zza
i s r et ur ned t o t he or der Pi zza() met hod.

4. The or der Pi zza() met hod has no i dea w hat k i nd of pi zza


w as c r eat ed, b ut i t k now s i t i s a pi zza and i t pr epar es,
b ak es, c ut s, and b ox es i t f or Et han and Joel .

Let’s check out how these pizzas are really made to order...
We’re just missing one thing: Pizzas!

Our Pizza Store isn’t going to be very popular without some


pizzas, so let’s implement them

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.

Now we just need some concrete subclasses...how about defining


New York and Chicago-style cheese pizzas?
You’ve waited long enough. Time for some pizzas!

It’s finally time to meet the Factory Method Pattern


A l l f ac t or y pat t er ns enc apsul at e ob jec t c r eat i on. The Fac t or y
Met hod Pat t er n enc apsul at es ob jec t c r eat i on b y l et t i ng sub c l asses
dec i de w hat ob jec t s t o c r eat e. Let ’s c hec k out t hese c l ass di agr ams t o
see w ho t he pl ay er s ar e i n t hi s pat t er n:

The Creator classes

The Product classes

View Creators and Products in Parallel


For ev er y c onc r et e Cr eat or , t her e’s t y pi c al l y a w hol e set of
pr oduc t s t hat i t c r eat es. Chi c ago pi zza c r eat or s c r eat e di f f er ent
t y pes of Chi c ago-st y l e pi zza, N ew Yor k pi zza c r eat or s c r eat e
di f f er ent t y pes of N ew Yor k —st y l e pi zza, and so on. In f ac t , w e c an
v i ew our set s of Cr eat or c l asses and t hei r c or r espondi ng Pr oduc t
c l asses as parallel h ierarc h ies .

Let ’s l ook at t he t w o par al l el c l ass hi er ar c hi es and see how t hey


r el at e:
N O TE
The factory method is the key to encapsulating this knowledge.

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.

Ok ay , now w r i t e t he f i v e m os t biz arre t hi ngs y ou c an t hi nk of t o


put on a pi zza. Then, y ou’l l b e r eady t o go i nt o b usi ness mak i ng
pi zza i n Cal i f or ni a!

__________________________________________________
___________

__________________________________________________
___________

__________________________________________________
___________

__________________________________________________
___________

__________________________________________________
___________

Factory Method Pattern defined


It ’s t i me t o r ol l out t he of f i c i al def i ni t i on of t he Fac t or y Met hod
Pat t er n:

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.

A s w i t h ev er y f ac t or y , t he Fac t or y Met hod Pat t er n gi v es us a w ay


t o enc apsul at e t he i nst ant i at i ons of c onc r et e t y pes. Look i ng at t he
c l ass di agr am b el ow , y ou c an see t hat t he ab st r ac t Cr eat or c l ass
gi v es y ou an i nt er f ac e w i t h a met hod f or c r eat i ng ob jec t s, al so
k now n as t he “f ac t or y met hod.” A ny ot her met hods i mpl ement ed i n
t he ab st r ac t Cr eat or ar e w r i t t en t o oper at e on pr oduc t s pr oduc ed
b y t he f ac t or y met hod. Onl y sub c l asses ac t ual l y i mpl ement t he
f ac t or y met hod and c r eat e pr oduc t s.

A s i n t he of f i c i al def i ni t i on, y ou’l l of t en hear dev el oper s say , “t he


Fac t or y Met hod pat t er n l et s sub c l asses dec i de w hi c h c l ass t o
i nst ant i at e.” Bec ause t he Cr eat or c l ass i s w r i t t en w i t hout
k now l edge of t he ac t ual pr oduc t s t hat w i l l b e c r eat ed, w e say
“dec i de” not b ec ause t he pat t er n al l ow s sub c l asses th em s elv es t o
dec i de, b ut r at her , b ec ause t he dec i si on ac t ual l y c omes dow n t o
w h ic h s ubc las s i s used t o c r eat e t he pr oduc t .

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

there are no Dumb Questions


Q: What’s the adv antage of the F actory Method Pattern when
y ou only hav e one ConcreteCreator?

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 ).

Q: Would it be correct to say that our NY and Chicago stores are


implemented using Simple F actory ? They look j ust like it.

A: They ’r e si mi l ar , b ut used i n di f f er ent w ay s. Ev en t hough t he


i mpl ement at i on of eac h c onc r et e st or e l ook s a l ot l i k e t he
Si mpl ePi zzaFac t or y , r ememb er t hat t he c onc r et e st or es ar e
ex t endi ng a c l ass t hat has def i ned c r eat ePi zza() as an ab st r ac t
met hod. It i s up t o eac h st or e t o def i ne t he b ehav i or of t he
c r eat ePi zza() met hod. In Si mpl e Fac t or y , t he f ac t or y i s anot her
ob jec t t hat i s c omposed w i t h t he Pi zzaSt or e.

Q: Are the factory method and the Creator class alway s


abstract?

A: N o, y ou c an def i ne a def aul t f ac t or y met hod t o pr oduc e some


c onc r et e pr oduc t . Then y ou al w ay s hav e a means of c r eat i ng
pr oduc t s ev en i f t her e ar e no sub c l asses of t he Cr eat or c l ass.

Q: Each store can make four different kinds of pizzas based on


the ty pe passed in. Do all concrete creators make multiple
products, or do they sometimes j ust make one?

A: W e i mpl ement ed w hat i s k now n as t he par amet er i zed f ac t or y


met hod. It c an mak e mor e t han one ob jec t b ased on a par amet er
passed i n, as y ou not i c ed. Of t en, how ev er , a f ac t or y just pr oduc es
one ob jec t and i s not par amet er i zed. Bot h ar e v al i d f or ms of t he
pat t er n.

Q: Y our parameterized ty pes don’t seem “ty pe-safe.” I ’m j ust


passing in a String! What if I asked for a “CalmPizza”?

A: You ar e c er t ai nl y c or r ec t , and t hat w oul d c ause w hat w e c al l i n


t he b usi ness a “r unt i me er r or .” Ther e ar e sev er al ot her mor e
sophi st i c at ed t ec hni ques t hat c an b e used t o mak e par amet er s mor e
“t y pe saf e”—i n ot her w or ds, t o ensur e er r or s i n par amet er s c an b e
c aught at c ompi l e t i me. For i nst anc e, y ou c an c r eat e ob jec t s t hat
r epr esent t he par amet er t y pes, use st at i c c onst ant s, or use enums.

Q: I ’m still a bit confused about the difference between Simple


F actory and F actory Method. They look v ery similar, except
that in F actory Method, the class that returns the pizza is a
subclass. Can y ou explain?

A: You’r e r i ght t hat t he sub c l asses do l ook a l ot l i k e Si mpl e Fac t or y ;


how ev er , t hi nk of Si mpl e Fac t or y as a one-shot deal , w hi l e w i t h
Fac t or y Met hod y ou ar e c r eat i ng a f r amew or k t hat l et s t he
sub c l asses dec i de w hi c h i mpl ement at i on w i l l b e used. For ex ampl e,
t he or der Pi zza() met hod i n t he Fac t or y Met hod Pat t er n pr ov i des a
gener al f r amew or k f or c r eat i ng pi zzas t hat r el i es on a f ac t or y
met hod t o ac t ual l y c r eat e t he c onc r et e c l asses t hat go i nt o mak i ng a
pi zza. By sub c l assi ng t he Pi zzaSt or e c l ass, y ou dec i de w hat c onc r et e
pr oduc t s go i nt o mak i ng t he pi zza t hat or der Pi zza() r et ur ns.
Compar e t hat w i t h Si mpl e Fac t or y , w hi c h gi v es y ou a w ay t o
enc apsul at e ob jec t c r eat i on, b ut doesn’t gi v e y ou t he f l ex i b i l i t y of
Fac t or y Met hod b ec ause t her e i s no w ay t o v ar y t he pr oduc t s y ou’r e
c r eat i ng.
Guru a nd S tud e nt...

Guru: Tell m e about y our training.

S tud e nt: Guru, I h av e tak en m y s tudy of “enc aps ulate w h at


v aries ” furth er.

Guru: Go on...

S tud e nt: I h av e learned th at one c an enc aps ulate th e c ode th at


c reates objec ts . Wh en y ou h av e c ode th at ins tantiates c onc rete
c las s es , th is is an area of freq uent c h ange. I ’v e learned a tec h niq ue
c alled “fac tories ” th at allow s y ou to enc aps ulate th is beh av ior of
ins tantiation.

Guru: And th es e “fac tories ,” of w h at benefit are th ey ?

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.

Guru: Yes , y our OO ins tinc ts are grow ing. Do y ou h av e any


q ues tions for y our guru today ?

S tud e nt: Guru, I k now th at by enc aps ulating objec t c reation I am


c oding to abs trac tions and dec oupling m y c lient c ode from ac tual
im plem entations . But m y fac tory c ode m us t s till us e c onc rete
c las s es to ins tantiate real objec ts . Am I not pulling th e w ool ov er m y
ow n ey es ?

Guru: Objec t c reation is a reality of life; w e m us t c reate objec ts or


w e w ill nev er c reate a s ingle Jav a applic ation. But, w ith
k now ledge of th is reality , w e c an des ign our c ode s o th at w e h av e
c orralled th is c reation c ode lik e th e s h eep w h os e w ool y ou w ould
pull ov er y our ey es . Onc e c orralled, w e c an protec t and c are for th e
c reation c ode. I f w e let our c reation c ode run w ild, th en w e w ill
nev er c ollec t its “w ool.”

S tud e nt: Guru, I s ee th e truth in th is .

Guru: As I k new y ou w ould. Now , pleas e go and m editate on objec t


dependenc ies .

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?

Looking at object dependencies


W hen y ou di r ec t l y i nst ant i at e an ob jec t , y ou ar e dependi ng on i t s
c onc r et e c l ass. Tak e a l ook at our v er y dependent Pi zzaSt or e one
page b ac k . It c r eat es al l t he pi zza ob jec t s r i ght i n t he Pi zzaSt or e
c l ass i nst ead of del egat i ng t o a f ac t or y .

If w e dr aw a di agr am r epr esent i ng t hat v er si on of t he Pi zzaSt or e


and al l t he ob jec t s i t depends on, her e’s w hat i t l ook s l i k e:
The Dependency Inversion Principle
It shoul d b e pr et t y c l ear t hat r educ i ng dependenc i es t o c onc r et e
c l asses i n our c ode i s a “good t hi ng.” In f ac t , w e’v e got an OO desi gn
pr i nc i pl e t hat f or mal i zes t hi s not i on; i t ev en has a b i g, f or mal
name: Dependenc y I nv ers ion Princ iple.

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.

Her e’s t he gener al pr i nc i pl e:

A t f i r st , t hi s pr i nc i pl e sounds a l ot l i k e “Pr ogr am t o an i nt er f ac e,


not an i mpl ement at i on,” r i ght ? It i s si mi l ar ; how ev er , t he
Dependenc y Inv er si on Pr i nc i pl e mak es an ev en st r onger st at ement
ab out ab st r ac t i on. It suggest s t hat our hi gh-l ev el c omponent s
shoul d not depend on our l ow -l ev el c omponent s; r at her , t hey shoul d
both depend on ab st r ac t i ons.

N O TE
A “high-level” component is a class with behavior defined in
terms of other, “low-level” components.

For example, PizzaStore is a high-level component because its


behavior is defined in terms of pizzas — it creates all the
different pizza objects, and prepares, bakes, cuts, and boxes
them, while the pizzas it uses are low-level components.

But w hat t he hec k does t hat mean?

W el l , l et ’s st ar t b y l ook i ng agai n at t he pi zza st or e di agr am on t he


pr ev i ous page. Pi zzaSt or e i s our “hi gh-l ev el c omponent ” and t he
pi zza i mpl ement at i ons ar e our “l ow -l ev el c omponent s,” and c l ear l y
Pi zzaSt or e i s dependent on t he c onc r et e pi zza c l asses.

N ow , t hi s pr i nc i pl e t el l s us w e shoul d i nst ead w r i t e our c ode so


t hat w e ar e dependi ng on ab st r ac t i ons, not c onc r et e c l asses. That
goes f or b ot h our hi gh-l ev el modul es and our l ow -l ev el modul es.

But how do w e do t hi s? Let ’s t hi nk ab out how w e’d appl y t hi s


pr i nc i pl e t o our v er y dependent Pi zzaSt or e i mpl ement at i on...

Applying the Principle


N ow , t he mai n pr ob l em w i t h t he v er y dependent Pi zzaSt or e i s t hat
i t depends on ev er y t y pe of pi zza b ec ause i t ac t ual l y i nst ant i at es
c onc r et e t y pes i n i t s or der Pi zza() met hod.

W hi l e w e’v e c r eat ed an ab st r ac t i on, Pi zza, w e’r e nev er t hel ess


c r eat i ng c onc r et e Pi zzas i n t hi s c ode, so w e don’t get a l ot of
l ev er age out of t hi s ab st r ac t i on.

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 .

So, af t er w e’v e appl i ed t he Fac t or y Met hod Pat t er n, our di agr am


l ook s l i k e t hi s:
A f t er appl y i ng Fac t or y Met hod, y ou’l l not i c e t hat our hi gh-l ev el
c omponent , t he Pi zzaSt or e, and our l ow -l ev el c omponent s, t he
pi zzas, b ot h depend on Pi zza, t he ab st r ac t i on. Fac t or y Met hod i s not
t he onl y t ec hni que f or adher i ng t o t he Dependenc y Inv er si on
Pr i nc i pl e, b ut i t i s one of t he mor e pow er f ul ones.

Where’s the “inv ersion” in Dependency I nv ersion Principle?

The “i nv er si on” i n t he name Dependenc y Inv er si on Pr i nc i pl e i s


t her e b ec ause i t i nv er t s t he w ay y ou t y pi c al l y mi ght t hi nk ab out
y our OO desi gn. Look at t he di agr am on t he pr ev i ous page. N ot i c e
t hat t he l ow -l ev el c omponent s now depend on a hi gher -l ev el
ab st r ac t i on. Li k ew i se, t he hi gh-l ev el c omponent i s al so t i ed t o t he
same ab st r ac t i on. So, t he t op-t o-b ot t om dependenc y c har t w e dr ew a
c oupl e of pages b ac k has i nv er t ed i t sel f , w i t h b ot h hi gh-l ev el and
l ow -l ev el modul es now dependi ng on t he ab st r ac t i on.

Let ’s al so w al k t hr ough t he t hi nk i ng b ehi nd t he t y pi c al desi gn


pr oc ess and see how i nt r oduc i ng t he pr i nc i pl e c an i nv er t t he w ay
w e t hi nk ab out t he desi gn...

Inverting your thinking...


Ok ay , so y ou need t o i mpl ement a Pi zza St or e. W hat ’s t he f i r st
t hought t hat pops i nt o y our head?
Ri ght , y ou st ar t at t he t op and f ol l ow t hi ngs dow n t o t he c onc r et e
c l asses. But , as y ou’v e seen, y ou don’t w ant y our pi zza st or e t o k now
ab out t he c onc r et e pi zza t y pes, b ec ause t hen i t ’l l b e dependent on
al l t hose c onc r et e c l asses!

N ow , l et ’s “i nv er t ” y our t hi nk i ng...i nst ead of st ar t i ng at t he t op,


st ar t at t he Pi zzas and t hi nk ab out w hat y ou c an ab st r ac t .

Ri ght ! You ar e t hi nk i ng ab out t he ab st r ac t i on Piz z a. So now , go


b ac k and t hi nk ab out t he desi gn of t he Pi zza St or e agai n.

Cl ose. But t o do t hat y ou’l l hav e t o r el y on a f ac t or y t o get t hose


c onc r et e c l asses out of y our Pi zza St or e. Onc e y ou’v e done t hat , y our
di f f er ent c onc r et e pi zza t y pes depend onl y on an ab st r ac t i on, and so
does y our st or e. W e’v e t ak en a desi gn w her e t he st or e depended on
c onc r et e c l asses and i nv er t ed t hose dependenc i es (al ong w i t h y our
t hi nk i ng).

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


The f ol l ow i ng gui del i nes c an hel p y ou av oi d OO desi gns t hat
v i ol at e t he Dependenc y Inv er si on Pr i nc i pl e:

N o v ar i ab l e shoul d hol d a r ef er enc e t o a c onc r et e c l ass.

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 c l ass shoul d der i v e f r om a c onc r et e c l ass.


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

N o met hod shoul d ov er r i de an i mpl ement ed met hod of


any of i t s b ase c l asses.

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!

You’r e ex ac t l y r i ght ! Li k e many of our pr i nc i pl es, t hi s i s a


gui del i ne y ou shoul d st r i v e f or , r at her t han a r ul e y ou shoul d
f ol l ow al l t he t i me. Cl ear l y , ev er y si ngl e Jav a pr ogr am ev er
w r i t t en v i ol at es t hese gui del i nes!

But , i f y ou i nt er nal i ze t hese gui del i nes and hav e t hem i n t he b ac k


of y our mi nd w hen y ou desi gn, y ou’l l k now w hen y ou ar e v i ol at i ng
t he pr i nc i pl e and y ou’l l hav e a good r eason f or doi ng so. For
i nst anc e, i f y ou hav e a c l ass t hat i sn’t l i k el y t o c hange, and y ou
k now i t , t hen i t ’s not t he end of t he w or l d i f y ou i nst ant i at e a
c onc r et e c l ass i n y our c ode. Thi nk ab out i t ; w e i nst ant i at e St r i ng
ob jec t s al l t he t i me w i t hout t hi nk i ng t w i c e. Does t hat v i ol at e t he
pr i nc i pl e? Yes. Is t hat ok ay ? Yes. W hy ? Bec ause St r i ng i s v er y
unl i k el y t o c hange.

If , on t he ot her hand, a c l ass y ou w r i t e i s l i k el y t o c hange, y ou hav e


some good t ec hni ques l i k e Fac t or y Met hod t o enc apsul at e t hat
c hange.

Meanwhile, back at the Pizza Store...


The desi gn f or t he Pi zza St or e i s r eal l y shapi ng up: i t ’s got a
f l ex i b l e f r amew or k and i t does a good job of adher i ng t o desi gn
pr i nc i pl es.

N ow , t he k ey t o Ob jec t v i l l e Pi zza’s suc c ess has al w ay s b een f r esh,


qual i t y i ngr edi ent s, and w hat y ou’v e di sc ov er ed i s t hat w i t h t he
new f r amew or k y our f r anc hi ses hav e b een f ol l ow i ng y our
proc edures , b ut a f ew f r anc hi ses hav e b een sub st i t ut i ng i nf er i or
i ngr edi ent s i n t hei r pi zzas t o l ow er c ost s and i nc r ease t hei r
mar gi ns. You k now y ou’v e got t o do somet hi ng, b ec ause i n t he l ong
t er m t hi s i s goi ng t o hur t t he Ob jec t v i l l e b r and!

N O TE
That is, the baking, the cutting, the boxing, and so on...

Ensuring consistency in your ingredients


So how ar e y ou goi ng t o ensur e eac h f r anc hi se i s usi ng qual i t y
i ngr edi ent s? You’r e goi ng t o b ui l d a f ac t or y t hat pr oduc es t hem and
shi ps t hem t o y our f r anc hi ses!

N ow t her e’s onl y one pr ob l em w i t h t hi s pl an: t he f r anc hi ses ar e


l oc at ed i n di f f er ent r egi ons and w hat i s r ed sauc e i n N ew Yor k i s
not r ed sauc e i n Chi c ago. So, y ou hav e one set of i ngr edi ent s t hat
needs t o b e shi pped t o N ew Yor k and a different set t hat needs t o b e
shi pped t o Chi c ago. Let ’s t ak e a c l oser l ook :

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?

For t hi s t o w or k , y ou’r e goi ng t o hav e t o f i gur e out how t o handl e


f ami l i es of i ngr edi ent s.

N O TE
In total, these three regions make up ingredient families, with
each region implementing a complete family of ingredients.

Building the ingredient factories


N ow w e’r e goi ng t o b ui l d a f ac t or y t o c r eat e our i ngr edi ent s; t he
f ac t or y w i l l b e r esponsi b l e f or c r eat i ng eac h i ngr edi ent i n t he
i ngr edi ent f ami l y . In ot her w or ds, t he f ac t or y w i l l need t o c r eat e
dough, sauc e, c heese, and so on... You’l l see how w e ar e goi ng t o
handl e t he r egi onal di f f er enc es shor t l y .

Let ’s st ar t b y def i ni ng an i nt er f ac e f or t he f ac t or y t hat i s goi ng t o


c r eat e al l our i ngr edi ent s:

With that interface, here’s what we’re going to do:


1 . Bui l d a f ac t or y f or eac h r egi on. To do t hi s, y ou’l l c r eat e a
sub c l ass of Pi zzaIngr edi ent Fac t or y t hat i mpl ement s eac h
c r eat e met hod.

2. Impl ement a set of i ngr edi ent c l asses t o b e used w i t h t he


f ac t or y , l i k e Reggi anoCheese, RedPepper s, and
Thi c k Cr ust Dough. These c l asses c an b e shar ed among
r egi ons w her e appr opr i at e.

3. Then w e st i l l need t o hook al l t hi s up b y w or k i ng our new


i ngr edi ent f ac t or i es i nt o our ol d Pi zzaSt or e c ode.

Building the New York ingredient factory


Ok ay , her e’s t he i mpl ement at i on f or t he N ew Yor k i ngr edi ent
f ac t or y . Thi s f ac t or y spec i al i zes i n Mar i nar a Sauc e, Reggi ano
Cheese, Fr esh Cl ams, et c .

SH AR PEN YO U R PEN C IL
Write the ChicagoPizzaIngredientFactory. You can reference the classes
below in your implementation:

Reworking the pizzas...


W e’v e got our f ac t or i es al l f i r ed up and r eady t o pr oduc e qual i t y
i ngr edi ent s; now w e just need t o r ew or k our Pi zzas so t hey onl y use
f ac t or y -pr oduc ed i ngr edi ent s. W e’l l st ar t w i t h our ab st r ac t Pi zza
c l ass:

Reworking the pizzas, continued...


N ow t hat y ou’v e got an ab st r ac t Pi zza c l ass t o w or k f r om, i t ’s t i me t o
c r eat e t he N ew Yor k — and Chi c ago-st y l e Pi zzas—onl y t hi s t i me
ar ound, t hey ’l l get t hei r i ngr edi ent s st r ai ght f r om t he f ac t or y . The
f r anc hi sees’ day s of sk i mpi ng on i ngr edi ent s ar e ov er !

W hen w e w r ot e t he Fac t or y Met hod c ode, w e had a N YCheesePi zza


and a Chi c agoCheesePi zza c l ass. If y ou l ook at t he t w o c l asses, t he
onl y t hi ng t hat di f f er s i s t he use of r egi onal i ngr edi ent s. The pi zzas
ar e made just t he same (dough + sauc e + c heese). The same goes f or
t he ot her pi zzas: V eggi e, Cl am, and so on. They al l f ol l ow t he same
pr epar at i on st eps; t hey just hav e di f f er ent i ngr edi ent s.

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.

Her e’s t he CheesePi zza:

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.

Let ’s c hec k out t he Cl amPi zza as w el l :

Revisiting our pizza stores


W e’r e al most t her e; w e just need t o mak e a qui c k t r i p t o our
f r anc hi se st or es t o mak e sur e t hey ar e usi ng t he c or r ec t Pi zzas. W e
al so need t o gi v e t hem a r ef er enc e t o t hei r l oc al i ngr edi ent
f ac t or i es:

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.

What have we done?


That w as qui t e a ser i es of c ode c hanges; w hat ex ac t l y di d w e do?

W e pr ov i ded a means of c r eat i ng a f ami l y of i ngr edi ent s f or pi zzas


b y i nt r oduc i ng a new t y pe of f ac t or y c al l ed an Abs trac t Fac tory .
A n A b st r ac t Fac t or y gi v es us an i nt er f ac e f or c r eat i ng a f ami l y of
pr oduc t s. By w r i t i ng c ode t hat uses t hi s i nt er f ac e, w e dec oupl e our
c ode f r om t he ac t ual f ac t or y t hat c r eat es t he pr oduc t s. That al l ow s
us t o i mpl ement a v ar i et y of f ac t or i es t hat pr oduc e pr oduc t s meant
f or di f f er ent c ont ex t s—suc h as di f f er ent r egi ons, di f f er ent
oper at i ng sy st ems, or di f f er ent l ook and f eel s.

Bec ause our c ode i s dec oupl ed f r om t he ac t ual pr oduc t s, w e c an


sub st i t ut e di f f er ent f ac t or i es t o get di f f er ent b ehav i or s (l i k e
get t i ng mar i nar a i nst ead of pl um t omat oes).

A n A b st r ac t Fac t or y pr ov i des an i nt er f ac e f or a f ami l y of pr oduc t s.


W hat ’s a f ami l y ? In our c ase, i t ’s al l t he t hi ngs w e need t o mak e a
pi zza: dough, sauc e, c heese, meat s, and v eggi es.

Fr om t he ab st r ac t f ac t or y , w e der i v e one or mor e c onc r et e


f ac t or i es t hat pr oduc e t he same pr oduc t s, b ut w i t h di f f er ent
i mpl ement at i ons.

W e t hen w r i t e our c ode so t hat i t uses t he f ac t or y t o c r eat e


pr oduc t s. By passi ng i n a v ar i et y of f ac t or i es, w e get a v ar i et y of
i mpl ement at i ons of t hose pr oduc t s. But our c l i ent c ode st ay s t he
same.

More pizza for Ethan and Joel...

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...

The f i r st par t of t he or der pr oc ess hasn’t c hanged at al l . Let ’s f ol l ow


Et han’s or der agai n:

From here things change, because we are using an ingredient


factory
Abstract Factory Pattern defined
W e’r e addi ng y et anot her f ac t or y pat t er n t o our pat t er n f ami l y ,
one t hat l et s us c r eat e f ami l i es of pr oduc t s. Let ’s c hec k out t he
of f i c i al def i ni t i on f or t hi s pat t er n:

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

W e’v e c er t ai nl y seen t hat A b st r ac t Fac t or y al l ow s a c l i ent t o use


an ab st r ac t i nt er f ac e t o c r eat e a set of r el at ed pr oduc t s w i t hout
k now i ng (or c ar i ng) ab out t he c onc r et e pr oduc t s t hat ar e ac t ual l y
pr oduc ed. In t hi s w ay , t he c l i ent i s dec oupl ed f r om any of t he
spec i f i c s of t he c onc r et e pr oduc t s. Let ’s l ook at t he c l ass di agr am t o
see how t hi s al l hol ds t oget her :

That’s a fairly complicated class diagram; let’s look at it all in


terms of our PizzaStore:
I s that a factory method lurking inside the Abstract F actory ?

Good c at c h! Yes, of t en t he met hods of an A b st r ac t Fac t or y ar e


i mpl ement ed as f ac t or y met hods. It mak es sense, r i ght ? The job of an
A b st r ac t Fac t or y i s t o def i ne an i nt er f ac e f or c r eat i ng a set of
pr oduc t s. Eac h met hod i n t hat i nt er f ac e i s r esponsi b l e f or c r eat i ng
a c onc r et e pr oduc t , and w e i mpl ement a sub c l ass of t he A b st r ac t
Fac t or y t o suppl y t hose i mpl ement at i ons. So, f ac t or y met hods ar e a
nat ur al w ay t o i mpl ement y our pr oduc t met hods i n y our ab st r ac t
f ac t or i es.
PAT T ER N S EXPO SED
This week’s interview: Factory Method and Abstract Factory, on each other

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.

HeadFirst: Don’t be miffed, we wanted to interview you together so we


could help clear up any confusion about who’s who for the readers. You do
have similarities, and I’ve heard that people sometimes get you confused.

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: Can you explain more about that, Factory Method?

Factory Method: Sure. Both Abstract Factory and I create objects—that’s


our job. But I do it through inheritance...

Abstract Factory: ...and I do it through object composition.

Factory Method: Right. So that means, to create objects using Factory


Method, you need to extend a class and provide an implementation for a
factory method.

HeadFirst: And that factory method does what?

Factory Method: It creates objects, of course! I mean, the whole point of


the Factory Method Pattern is that you’re using a subclass to do your
creation for you. In that way, clients only need to know the abstract type they
are using; the subclass worries about the concrete type. So, in other
words, I keep clients decoupled from the concrete types.

Abstract Factory: And I do too, only I do it in a different way.

HeadFirst: Go on, Abstract Factory...you said something about object


composition?

Abstract Factory: I provide an abstract type for creating a family of


products. Subclasses of this type define how those products are produced.
To use the factory, you instantiate one and pass it into some code that is
written against the abstract type. So, like Factory Method, my clients are
decoupled from the actual concrete products they use.

HeadFirst: Oh, I see, so another advantage is that you group together a set
of related products.

Abstract Factory: T hat’s right.

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?

Abstract Factory: T hat’s true; my interface has to change if new products


are added, which I know people don’t like to do....

Factory Method: <snicker>

Abstract Factory: What are you snickering at, Factory Method?

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.

Abstract Factory: Yeah, but I need a big interface because I am used to


creating entire families of products. You’re only creating one product, so
you don’t really need a big interface, you just need one method.

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...

Factory Method: ...while in my case I usually implement code in the


abstract creator that makes use of the concrete types the subclasses
create.

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?

Abstract Factory: T hanks. Remember me, Abstract Factory, and use me


whenever you have families of products you need to create and you want to
make sure your clients create products that belong together.

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!

Factory Method and Abstract Factory compared


N O TE
The product subclasses create parallel sets of product families.
Here we have a New York ingredient family and a Chicago
family.

Tools for your Design Toolbox


In t hi s c hapt er , w e added t w o mor e t ool s t o y our t ool b ox : Fac t or y
Met hod and A b st r ac t Fac t or y . Bot h pat t er ns enc apsul at e ob jec t
c r eat i on and al l ow y ou t o dec oupl e y our c ode f r om c onc r et e t y pes.
B U L L ET PO IN T S

All factories encapsulate object creation.

Simple Factory, while not a bona fide design pattern, is a simple


way to decouple your clients from concrete classes.

Factory Method relies on inheritance: object creation is


delegated to subclasses, which implement the factory method
to create objects.

Abstract Factory relies on object composition: object creation is


implemented in methods exposed in the factory interface.

All factory patterns promote loose coupling by reducing the


dependency of your application on concrete classes.

T he intent of Factory Method is to allow a class to defer


instantiation to its subclasses.

T he intent of Abstract Factory is to create families of related


objects without having to depend on their concrete classes.

T he Dependency Inversion Principle guides us to avoid


dependencies on concrete types and to strive for abstractions.

Factories are a powerful technique for coding to abstractions,


not concrete classes.

Design Patterns Crossword


It ’s b een a l ong c hapt er . Gr ab a sl i c e of Pi zza and r el ax w hi l e doi ng
t hi s c r ossw or d; al l of t he sol ut i on w or ds ar e f r om t hi s c hapt er .

ACROSS

1 . In Fac t or y Met hod, eac h f r anc hi se i s a ________.

4. In Fac t or y Met hod, w ho dec i des w hi c h c l ass t o i nst ant i at e?

6. Rol e of Pi zzaSt or e i n t he Fac t or y Met hod Pat t er n.

7 . A l l N ew Yor k —st y l e pi zzas use t hi s k i nd of c heese.

8. In A b st r ac t Fac t or y , eac h i ngr edi ent f ac t or y i s a _______.

9. W hen y ou use new, y ou ar e pr ogr ammi ng t o an ___________.

1 1 . c r eat ePi zza() i s a ____________.

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.

1 4. W hen a c l ass i nst ant i at es an ob jec t f r om a c onc r et e c l ass, i t ’s


___________ on t hat ob jec t .

1 5. A l l f ac t or y pat t er ns al l ow us t o __________ ob jec t c r eat i on.

DOWN

2. W e used ___________ i n Si mpl e Fac t or y and A b st r ac t Fac t or y ,


and i nher i t anc e i n Fac t or y Met hod.

3. A b st r ac t Fac t or y c r eat es a ___________ of pr oduc t s.

5. N ot a REA L f ac t or y pat t er n, b ut handy nonet hel ess.

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:

Design Puzzle Solution


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.

Ok ay , now w r i t e t he f i v e si l l i est t hi ngs y ou c an t hi nk of t o put on a


pi zza. Then, y ou’l l b e r eady t o go i nt o b usi ness mak i ng pi zza i n
Cal i f or ni a!
SH AR PEN YO U R PEN C IL
SO L U T IO N
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 for you to make a
count of the number of concrete pizza classes this class is dependent on.
If you added California-style pizzas to PizzaStore, how many classes would
it be dependent on then? Here’s our solution.

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:

public class ChicagoPizzaIngredientFactory


implements PizzaIngredientFactory
{

public Dough createDough() {


return new ThickCrustDough();
}

public Sauce createSauce() {


return new PlumTomatoSauce();
}

public Cheese createCheese() {


return new MozzarellaCheese();
}

public Veggies[] createVeggies() {


Veggies veggies[] = { new BlackOlives(),
new Spinach(),
new Eggplant() };
return veggies;
}

public Pepperoni createPepperoni() {


return new SlicedPepperoni();
}

public Clams createClam() {


return new FrozenClams();
}
}

Design Patterns Crossword Solution


It ’s b een a l ong c hapt er . Gr ab a sl i c e of Pi zza and r el ax w hi l e doi ng
t hi s c r ossw or d; al l of t he sol ut i on w or ds ar e f r om t hi s c hapt er .
Her e’s t he sol ut i on.
Chapter 5. One-of-a-Kind Objects:
The Singleton Pattern

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: Ok ay , s o m ay be th ere are c las s es th at s h ould only be


ins tantiated onc e, but do I need a w h ole c h apter for th is ? Can’t I jus t
do th is by c onv ention or by global v ariables ? You k now , lik e in Jav a,
I c ould do it w ith a s tatic v ariable.

Guru: I n m any w ay s , th e S ingleton Pattern is a c onv ention for


ens uring one and only one objec t is ins tantiated for a giv en c las s . I f
y ou’v e got a better one, th e w orld w ould lik e to h ear about it; but
rem em ber, lik e all patterns , th e S ingleton Pattern is a tim e-tes ted
m eth od for ens uring only one objec t gets c reated. Th e S ingleton
Pattern als o giv es us a global point of ac c es s , jus t lik e a global
v ariable, but w ith out th e dow ns ides .

De v e lo p e r: Wh at dow ns ides ?

Guru: Well, h ere’s one exam ple: if y ou as s ign an objec t to a global


v ariable, th en th at objec t m igh t be c reated w h en y our applic ation
begins . Righ t? Wh at if th is objec t is res ourc e intens iv e and y our
applic ation nev er ends up us ing it? As y ou w ill s ee, w ith th e
S ingleton Pattern, w e c an c reate our objec ts only w h en th ey are
needed.

De v e lo p e r: Th is s till does n’t s eem lik e it s h ould be s o diffic ult.

Guru: I f y ou’v e got a good h andle on s tatic c las s v ariables and


m eth ods as w ell as ac c es s m odifiers , it’s not. But, in eith er c as e, it is
interes ting to s ee h ow a S ingleton w ork s , and, as s im ple as it
s ounds , S ingleton c ode is h ard to get righ t. Jus t as k y ours elf: h ow
do I prev ent m ore th an one objec t from being ins tantiated? I t’s not s o
obv ious , is it?

The Little Singleton

A small Socratic exercise in the style of The Little Lisper


How would you new MyObject();
create a single
object?

And, what if Yes, of course.


another object
wanted to create
a MyObject?
Could it call new
on MyObject
again?

So as long as we Yes. Well, only if it’s a public class.


have a class, can
we always
instantiate it one
or more times?

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
() {}

What does it I suppose it is a class that can’t be instantiated because it has a


mean? private constructor.

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()”.

MyClass is a class with a static method. We can call the static


Okay. It was just method like this:
MyClass.getInstance();
a thought.
What does this
mean?

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?

Wow, you sure can.


Very interesting.
What if we put
things together?
Now can I
instantiate a
MyClass?

public
MyClass
{

private
MyClass
() {}

public
static
MyClass
getInst
ance()
{

return
new
MyClass
();
}
}

So, now can you MyClass.getInstance();


think of a second
way to
instantiate an
object?

Can you finish Yes, I think so...


the code so that
only ONE
instance of
MyClass is ever
created?

Dissecting the classic Singleton Pattern


implementation
W AT C H IT !
If you’re just flipping through the book, don’t blindly type in this code; you’ll
see it has a few issues later in the chapter.

PAT T ER N S EXPO SED


This week’s interv iew: Confessions of a Singleton

HeadFirst: Today we are pleased to bring you an interview with a Singleton


object. Why don’t you begin by telling us a bit about yourself?

Singleton: Well, I’m totally unique; there is just one of me!

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.

HeadFirst: Tell us more…

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.

HeadFirst: Still, only one of your kind? T hat sounds lonely.

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”?

Singleton: Nope! I’m truly unique.

HeadFirst: Well, do developers swear an oath not to instantiate you more


than once?

Singleton: Of course not. T he truth be told…well, this is getting kind of


personal but…I have no public constructor.

HeadFirst: NO PUBLIC CONST RUCT OR! Oh, sorry, no public constructor?

Singleton: T hat’s right. My constructor is declared private.

HeadFirst: How does that work? How do you EVER get instantiated?

Singleton: You see, to get a hold of a Singleton object, you don’t


instantiate one, you just ask for an instance. So my class has a static
method called getInstance(). Call that, and I’ll show up at once, ready to
work. In fact, I may already be helping other objects when you request me.

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!

The Chocolate Factory


Ev er y one k now s t hat al l moder n c hoc ol at e f ac t or i es hav e
c omput er -c ont r ol l ed c hoc ol at e b oi l er s. The job of t he b oi l er i s t o
t ak e i n c hoc ol at e and mi l k , b r i ng t hem t o a b oi l , and t hen pass t hem
on t o t he nex t phase of mak i ng c hoc ol at e b ar s.
Her e’s t he c ont r ol l er c l ass f or Choc -O-Hol i c , Inc .’s i ndust r i al
st r engt h Choc ol at e Boi l er . Chec k out t he c ode; y ou’l l not i c e t hey ’v e
t r i ed t o b e v er y c ar ef ul t o ensur e t hat b ad t hi ngs don’t happen, l i k e
dr ai ni ng 500 gal l ons of unb oi l ed mi x t ur e, or f i l l i ng t he b oi l er
w hen i t ’s al r eady f ul l , or b oi l i ng an empt y b oi l er !

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.

How might things go wrong if more than one instance of ChocolateBoiler is


created in an application?

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?

Singleton Pattern defined


Now that y ou’v e got the classic implementation of Singleton in
y our head, it’s time to sit back, enj oy a bar of chocolate, and
check out the finer points of the Singleton Pattern.

Let’s start with the concise definition of the pattern:

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:

W hat ’s r eal l y goi ng on her e? W e’r e t ak i ng a c l ass and


l et t i ng i t manage a si ngl e i nst anc e of i t sel f . W e’r e al so
pr ev ent i ng any ot her c l ass f r om c r eat i ng a new i nst anc e
on i t s ow n. To get an i nst anc e, y ou’v e got t o go t hr ough t he
c l ass i t sel f .

W e’r e al so pr ov i di ng a gl ob al ac c ess poi nt t o t he i nst anc e:


w henev er y ou need an i nst anc e, just quer y t he c l ass and i t
w i l l hand y ou b ac k t he si ngl e i nst anc e. A s y ou’v e seen, w e
c an i mpl ement t hi s so t hat t he Si ngl et on i s c r eat ed i n a
l azy manner , w hi c h i s espec i al l y i mpor t ant f or r esour c e-
i nt ensi v e ob jec t s.

Okay , let’s check out the class diagram:

Hershey, PA, we have a problem...


I t looks like the Chocolate Boiler has let us down; despite the
fact we improv ed the code using the classic Singleton Pattern,
somehow the Chocolate Boiler’s fill() method was able to start
filling the boiler ev en though a batch of milk and chocolate was
already boiling! That’s 500 gallons of spilled milk (and
chocolate)! What happened!?

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

Make sure y ou check y our answer in “ BE


the JVM Solution” before continuing!
Dealing with multithreading
Our multithreading woes are almost triv ially fixed by making
getI nstance() a sy nchronized method:

Good poi nt , and i t ’s ac t ual l y a l i t t l e w or se t han y ou mak e out : t he


onl y t i me sy nc hr oni zat i on i s r el ev ant i s t he f i r st t i me t hr ough t hi s
met hod. In ot her w or ds, onc e w e’v e set t he uni queInst anc e v ar i ab l e
t o an i nst anc e of Si ngl et on, w e hav e no f ur t her need t o sy nc hr oni ze
t hi s met hod. A f t er t he f i r st t i me t hr ough, sy nc hr oni zat i on i s
t ot al l y unneeded ov er head!

Can we improve multithreading?


For most Jav a appl i c at i ons, w e ob v i ousl y need t o ensur e t hat t he
Si ngl et on w or k s i n t he pr esenc e of mul t i pl e t hr eads. But i t ’s
ex pensi v e t o sy nc hr oni ze t he get Inst anc e() met hod, so w hat do w e
do?

W el l , w e hav e a f ew opt i ons...

1. Do nothing if the performance of getInstance() isn’t critical to


your application.

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 .

2. Move to an eagerly created instance rather than a lazily


created one.

If y our appl i c at i on al w ay s c r eat es and uses an i nst anc e of t he


Si ngl et on, or t he ov er head of c r eat i on and r unt i me aspec t s of t he
Si ngl et on i sn’t oner ous, y ou may w ant t o c r eat e y our Si ngl et on
eager l y , l i k e t hi s:
U si ng t hi s appr oac h, w e r el y on t he JV M t o c r eat e t he uni que
i nst anc e of t he Si ngl et on w hen t he c l ass i s l oaded. The JV M
guar ant ees t hat t he i nst anc e w i l l b e c r eat ed b ef or e any t hr ead
ac c esses t he st at i c uni queInst anc e v ar i ab l e.

3. Use “double-checked locking” to reduce the use of


synchronization in getInstance().

W i t h doub l e-c hec k ed l oc k i ng, w e f i r st c hec k t o see i f an i nst anc e i s


c r eat ed, and i f not , THEN w e sy nc hr oni ze. Thi s w ay , w e onl y
sy nc hr oni ze t he f i r st t i me t hr ough, just w hat w e w ant .

Let ’s c hec k out t he c ode:

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!

If for some reason you’re using an old version of Java, unfortunately, in


Java version 1.4 and earlier, many JVMs contain implementations of the
volatile keyword that allow improper synchronization for double-checked
locking. If you must use a JVM earlier than Java 5, consider other methods
of implementing your Singleton.

Meanwhile, back at the Chocolate Factory...

W hi l e w e’v e b een of f di agnosi ng t he mul t i t hr eadi ng pr ob l ems, t he


c hoc ol at e b oi l er has b een c l eaned up and i s r eady t o go. But f i r st ,
w e hav e t o f i x t he mul t i t hr eadi ng pr ob l ems. W e hav e a f ew
sol ut i ons at hand, eac h w i t h di f f er ent t r adeof f s, so w hi c h sol ut i on
ar e w e goi ng t o empl oy ?
SH AR PEN YO U R PEN C IL
For each solution, describe its applicability to the problem of fixing the
Chocolate Boiler code:

Synchronize the getInstance() method:

____________________________________________________________
___

____________________________________________________________
___

Use eager instantiation:

____________________________________________________________
___

____________________________________________________________
___

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.

there are no Dumb Questions


Q: F or such a simple pattern consisting of only one class,
Singleton sure seems to hav e some problems.

A: W el l , w e w ar ned y ou up f r ont ! But don’t l et t he pr ob l ems


di sc our age y ou; w hi l e i mpl ement i ng Si ngl et ons c or r ec t l y c an b e
t r i c k y , af t er r eadi ng t hi s c hapt er y ou’r e now w el l i nf or med on t he
t ec hni ques f or c r eat i ng Si ngl et ons and shoul d use t hem w her ev er
y ou need t o c ont r ol t he numb er of i nst anc es y ou’r e c r eat i ng.

Q: Can’t I j ust create a class in which all methods and v ariables


are defined as static? Wouldn’t that be the same as a Singleton?

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.

Q: What about class loaders? I heard there’s a chance that two


class loaders could each end up with their own instance of
Singleton.

A: Yes, t hat i s t r ue as eac h c l ass l oader def i nes a namespac e. If y ou


hav e t w o or mor e c l ass l oader s, y ou c an l oad t he same c l ass mul t i pl e
t i mes (onc e i n eac h c l ass l oader ). N ow , i f t hat c l ass happens t o b e a
Si ngl et on, t hen si nc e w e hav e mor e t han one v er si on of t he c l ass,
w e al so hav e mor e t han one i nst anc e of Si ngl et on. So, i f y ou ar e
usi ng mul t i pl e c l ass l oader s and Si ngl et ons, b e c ar ef ul . One w ay
ar ound t hi s pr ob l em i s t o spec i f y t he c l ass l oader y our sel f .

Q: And reflection, and serialization/deserialization?

A: Yes, r ef l ec t i on and ser i al i zat i on/deser i al i zat i on c an al so pr esent


pr ob l ems w i t h Si ngl et ons. If y ou’r e an adv anc ed Jav a user usi ng
r ef l ec t i on, ser i al i zat i on, and deser i al i zat i on, y ou’l l need t o k eep
t hat i n mi nd.

Q: Earlier we talked about the loose coupling principle. I sn’t a


Singleton v iolating this? After all, ev ery obj ect in our code that
depends on the Singleton is going to be tightly coupled to that
v ery specific obj ect.

A: Yes, and i n f ac t t hi s i s a c ommon c r i t i c i sm of t he Si ngl et on


Pat t er n. The l oose c oupl i ng pr i nc i pl e say s t o “st r i v e f or l oosel y
c oupl ed desi gns b et w een ob jec t s t hat i nt er ac t .” It ’s easy f or
Si ngl et ons t o v i ol at e t hi s pr i nc i pl e: i f y ou mak e a c hange t o t he
Si ngl et on, y ou’l l l i k el y hav e t o mak e a c hange t o ev er y ob jec t
c onnec t ed t o i t .

Q: I ’v e alway s been taught that a class should do one thing and


one thing only . F or a class to do two things is considered bad OO
design. I sn’t a Singleton v iolating this too?

A: You w oul d b e r ef er r i ng t o t he Si ngl e Responsi b i l i t y Pr i nc i pl e,


and y es, y ou ar e c or r ec t : t he Si ngl et on i s r esponsi b l e not onl y f or
managi ng i t s one i nst anc e (and pr ov i di ng gl ob al ac c ess), b ut al so
f or w hat ev er i t s mai n r ol e i s i n y our appl i c at i on. So, c er t ai nl y y ou
c oul d ar gue i t i s t ak i ng on t w o r esponsi b i l i t i es. N ev er t hel ess, i t
i sn’t har d t o see t hat t her e i s ut i l i t y i n a c l ass managi ng i t s ow n
i nst anc e; i t c er t ai nl y mak es t he ov er al l desi gn si mpl er . In addi t i on,
many dev el oper s ar e f ami l i ar w i t h t he Si ngl et on Pat t er n as i t i s i n
w i de use. That sai d, some dev el oper s do f eel t he need t o ab st r ac t out
t he Si ngl et on f unc t i onal i t y .

Q: I wanted to subclass my Singleton code, but I ran into


problems. I s it okay to subclass a Singleton?

A: One pr ob l em w i t h sub c l assi ng a Si ngl et on i s t hat t he


c onst r uc t or i s pr i v at e. You c an’t ex t end a c l ass w i t h a pr i v at e
c onst r uc t or . So, t he f i r st t hi ng y ou’l l hav e t o do i s c hange y our
c onst r uc t or so t hat i t ’s pub l i c or pr ot ec t ed. But t hen, i t ’s not r eal l y
a Si ngl et on any mor e, b ec ause ot her c l asses c an i nst ant i at e i t .

If y ou do c hange y our c onst r uc t or , t her e’s anot her i ssue. The


i mpl ement at i on of Si ngl et on i s b ased on a st at i c v ar i ab l e, so i f y ou
do a st r ai ght f or w ar d sub c l ass, al l of y our der i v ed c l asses w i l l shar e
t he same i nst anc e v ar i ab l e. Thi s i s pr ob ab l y not w hat y ou had i n
mi nd. So, f or sub c l assi ng t o w or k , i mpl ement i ng a r egi st r y of sor t s
i s r equi r ed i n t he b ase c l ass.

But w hat ar e y ou r eal l y gai ni ng f r om sub c l assi ng a Si ngl et on? Li k e


most pat t er ns, Si ngl et on i s not nec essar i l y meant t o b e a sol ut i on
t hat c an f i t i nt o a l i b r ar y . In addi t i on, t he Si ngl et on c ode i s t r i v i al
t o add t o any ex i st i ng c l ass. Last , i f y ou ar e usi ng a l ar ge numb er of
Si ngl et ons i n y our appl i c at i on, y ou shoul d t ak e a har d l ook at y our
desi gn. Si ngl et ons ar e meant t o b e used spar i ngl y .

Q: I still don’t totally understand why global v ariables are worse


than a Singleton.

A: In Jav a, gl ob al v ar i ab l es ar e b asi c al l y st at i c r ef er enc es t o


ob jec t s. Ther e ar e a c oupl e of di sadv ant ages t o usi ng gl ob al
v ar i ab l es i n t hi s manner . W e’v e al r eady ment i oned one: t he i ssue of
l azy v er sus eager i nst ant i at i on. But w e need t o k eep i n mi nd t he
i nt ent of t he pat t er n: t o ensur e onl y one i nst anc e of a c l ass ex i st s
and t o pr ov i de gl ob al ac c ess. A gl ob al v ar i ab l e c an pr ov i de t he
l at t er , b ut not t he f or mer . Gl ob al v ar i ab l es al so t end t o enc our age
dev el oper s t o pol l ut e t he namespac e w i t h l ot s of gl ob al r ef er enc es
t o smal l ob jec t s. Si ngl et ons don’t enc our age t hi s i n t he same w ay ,
b ut c an b e ab used nonet hel ess.

Ah, good idea!

Many of t he pr ob l ems w e’v e di sc ussed—w or r y i ng ab out


sy nc hr oni zat i on, c l ass l oadi ng i ssues, r ef l ec t i on, and
ser i al i zat i on/deser i al i zat i on i ssues—c an al l b e sol v ed b y usi ng an
enum t o c r eat e y our Si ngl et on. Her e’s how y ou’d do t hat :

public enum Singleton {


UNIQUE_INSTANCE;
// more useful fields here
}
public class SingletonClient {
public static void main(String[] args) {
Singleton singleton = Singleton.UNIQUE_INSTANCE;
// use the singleton here
}
}

Yep, t hat ’s al l t her e i s t o i t . Si mpl est Si ngl et on ev er , r i ght ? N ow ,


y ou mi ght b e ask i ng, w hy di d w e go t hr ough al l t hat ear l i er w i t h
c r eat i ng a Si ngl et on c l ass w i t h a get Inst anc e() met hod and t hen
sy nc hr oni zi ng, and so on? W e di d t hat so y ou r eal l y , t r ul y
under st and how Si ngl et on w or k s. N ow t hat y ou k now , y ou c an go
of f and use enum w henev er y ou need a Si ngl et on, and st i l l b e ab l e
t o ac e t hat Jav a i nt er v i ew i f t he quest i on pops up: “How do y ou
i mpl ement a Si ngl et on w ith out usi ng enum?”

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.

Tools for your Design Toolbox


You’v e now added anot her pat t er n t o y our t ool b ox . Si ngl et on gi v es
y ou anot her met hod of c r eat i ng ob jec t s—i n t hi s c ase, uni que
ob jec t s.

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

T he Singleton Pattern ensures you have at most one instance


of a class in your application.

T he Singleton Pattern also provides a global access point to


that instance.

Java’s implementation of the Singleton Pattern makes use of a


private constructor, a static method combined with a static
variable.

Examine your performance and resource constraints and


carefully choose an appropriate Singleton implementation for
multithreaded applications (and we should consider all
applications multithreaded! ).

Beware of the double-checked locking implementation; it isn’t


thread safe in versions before Java 5.

Be careful if you are using multiple class loaders; this could


defeat the Singleton implementation and result in multiple
instances.

You can use Java’s enums to simplify your Singleton


implementation.

Design Patterns Crossword


Si t b ac k , open t hat c ase of c hoc ol at e t hat y ou w er e sent f or sol v i ng
t he mul t i t hr eadi ng pr ob l em, and hav e some dow nt i me w or k i ng on
t hi s l i t t l e c r ossw or d puzzl e; al l of t he sol ut i on w or ds ar e f r om t hi s
c hapt er .
ACROSS

3. Company t hat pr oduc es b oi l er s.

6. A n i nc or r ec t i mpl ement at i on c aused t hi s t o ov er f l ow .

7 . The Si ngl et on Pat t er n has one.

1 0. To t ot al l y def eat t he new c onst r uc t or , w e hav e t o dec l ar e t he


c onst r uc t or __________.

1 2. The c l assi c i mpl ement at i on doesn’t handl e t hi s.

1 3. Si ngl et on pr ov i des a si ngl e i nst anc e and __________ (t hr ee


w or ds).

1 4. A n easy w ay t o c r eat e Si ngl et ons i n Jav a.

1 5. The Si ngl et on w as emb ar r assed i t had no pub l i c __________.

1 6. A Si ngl et on i s a c l ass t hat manages an i nst anc e of ________.

DOWN

1 . A dded t o c hoc ol at e i n t he b oi l er .

2. Fl aw ed mul t i t hr eadi ng appr oac h i f not usi ng Jav a 5 or l at er (t w o


w or ds).

3. It w as “one of a k i nd.”

4. Mul t i pl e __________ c an c ause pr ob l ems (t w o w or ds).

5. If y ou don’t need t o w or r y ab out l azy i nst ant i at i on, y ou c an


c r eat e y our i nst anc e __________.

8. One adv ant age ov er gl ob al v ar i ab l es: ________ c r eat i on.

9. Choc ol at e c api t al of t he U SA .

1 1 . Si ngl et on ensur es onl y one of t hese ex i st s.

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:

Synchronize the getInstance() method:

A straightforward technique that is guaranteed to work. We don’t seem to


have

any performance concerns with the chocolate boiler, so this would be a


good choice.

Use eager instantiation:

We are always going to instantiate the chocolate boiler in our code, so


statically initializing

the instance would cause no concerns. T his solution would work as well
as the synchronized

method, although perhaps be less obvious to a developer familar with the


standard pattern.

Double-checked locking:

Given we have no performance concerns, double-checked locking seems


like overkill. In

addition, we’d have to ensure that we are running at least Java 5.

Design Patterns Crossword Solution


Chapter 6. Encapsulating
Invocation: The Command Pattern

I n this chapter, we take encapsulation to a whole new lev el:


we’re going to encapsulate method inv ocation. That ’s r i ght —b y
enc apsul at i ng met hod i nv oc at i on, w e c an c r y st al l i ze pi ec es of
c omput at i on so t hat t he ob jec t i nv ok i ng t he c omput at i on doesn’t
need t o w or r y ab out how t o do t hi ngs, i t just uses our c r y st al l i zed
met hod t o get i t done. W e c an al so do some w i c k edl y smar t t hi ngs
w i t h t hese enc apsul at ed met hod i nv oc at i ons, l i k e sav e t hem aw ay
f or l oggi ng or r euse t hem t o i mpl ement undo f unc t i onal i t y i n our
c ode.

Home Automation or Bust, Inc.

Free hardware! Let’s check out the Remote Control...

Taking a look at the vendor classes


Let ’s c hec k out t he v endor c l asses t he CEO at t ac hed t o hi s emai l .
These shoul d gi v e y ou some i dea of t he i nt er f ac es of t he ob jec t s w e
need t o c ont r ol f r om t he r emot e.
It l ook s l i k e w e hav e qui t e a set of c l asses her e, and not a l ot of
i ndust r y ef f or t t o c ome up w i t h a set of c ommon i nt er f ac es. N ot
onl y t hat , i t sounds l i k e w e c an ex pec t mor e of t hese c l asses i n t he
f ut ur e. Desi gni ng a r emot e c ont r ol A PI i s goi ng t o b e i nt er est i ng.
Let ’s get on t o t he desi gn.

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...

Mary : Yes, I t hought w e’d see a b unc h of c l asses w i t h on() and of f ()


met hods, b ut her e w e’v e got met hods l i k e di m(), set Temper at ur e(),
set V ol ume(), and set Input Channel (), and w at er On().

Sue: N ot onl y t hat , i t sounds l i k e w e c an ex pec t mor e v endor


c l asses i n t he f ut ur e w i t h met hods just as di v er se.

Mary : I t hi nk i t ’s i mpor t ant w e v i ew t hi s as a separ at i on of


c onc er ns.

Sue: Meani ng?

Mary : W hat I mean i s t hat t he r emot e shoul d k now how t o


i nt er pr et b ut t on pr esses and mak e r equest s, b ut i t shoul dn’t k now a
l ot ab out home aut omat i on or how t o t ur n on a hot t ub .

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 ?

Mary : I’m not sur e, b ut w e don’t w ant t he r emot e t o hav e t o k now


t he spec i f i c s of t he v endor c l asses.

Sue: W hat do y ou mean?

Mary : W e don’t w ant t he r emot e t o c onsi st of a set of i f st at ement s,


l i k e “i f sl ot 1 == Li ght , t hen l i ght .on(), el se i f sl ot 1 == Hot t ub t hen
hot t ub .jet sOn()”. W e k now t hat i s a b ad desi gn.

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.

Joe: The Command Pat t er n al l ow s y ou t o dec oupl e t he r equest er of


an ac t i on f r om t he ob jec t t hat ac t ual l y per f or ms t he ac t i on. So,
her e t he r equest er w oul d b e t he r emot e c ont r ol and t he ob jec t t hat
per f or ms t he ac t i on w oul d b e an i nst anc e of one of y our v endor
c l asses.

Sue: How i s t hat possi b l e? How c an w e dec oupl e t hem? A f t er al l ,


w hen I pr ess a b ut t on, t he r emot e has t o t ur n on a l i ght .

Joe: You c an do t hat b y i nt r oduc i ng c om m and objec ts i nt o y our


desi gn. A c ommand ob jec t enc apsul at es a r equest t o do somet hi ng
(l i k e t ur n on a l i ght ) on a spec i f i c ob jec t (say , t he l i v i ng r oom l i ght
ob jec t ). So, i f w e st or e a c ommand ob jec t f or eac h b ut t on, w hen t he
b ut t on i s pr essed w e ask t he c ommand ob jec t t o do some w or k . The
r emot e doesn’t hav e any i dea w hat t he w or k i s, i t just has a
c ommand ob jec t t hat k now s how t o t al k t o t he r i ght ob jec t t o get t he
w or k done. So, y ou see, t he r emot e i s dec oupl ed f r om t he l i ght
ob jec t !

Sue: Thi s c er t ai nl y sounds l i k e i t ’s goi ng i n t he r i ght di r ec t i on.

Mary : St i l l , I’m hav i ng a har d t i me w r appi ng my head ar ound t he


pat t er n.

Joe: Gi v en t hat t he ob jec t s ar e so dec oupl ed, i t ’s a l i t t l e di f f i c ul t t o


pi c t ur e how t he pat t er n ac t ual l y w or k s.

Mary : Let me see i f I at l east hav e t he r i ght i dea: usi ng t hi s pat t er n,


w e c oul d c r eat e an A PI i n w hi c h t hese c ommand ob jec t s c an b e
l oaded i nt o b ut t on sl ot s, al l ow i ng t he r emot e c ode t o st ay v er y
si mpl e. A nd t he c ommand ob jec t s enc apsul at e how t o do a home
aut omat i on t ask al ong w i t h t he ob jec t t hat needs t o do i t .

Joe: Yes, I t hi nk so. I al so t hi nk t hi s pat t er n c an hel p y ou w i t h t hat


undo b ut t on, b ut I hav en’t st udi ed t hat par t y et .

Mary : Thi s sounds r eal l y enc our agi ng, b ut I t hi nk I hav e a b i t of


w or k t o do t o r eal l y “get ” t he pat t er n.

Sue: Me t oo.

Meanwhile, back at the Diner..., or, A brief introduction to


the Command Pattern
A s Joe sai d, i t i s a l i t t l e har d t o under st and t he Command Pat t er n b y
just hear i ng i t s desc r i pt i on. But don’t f ear , w e hav e some f r i ends
r eady t o hel p: r ememb er our f r i endl y di ner f r om Chapt er 1 ? It ’s
b een a w hi l e si nc e w e v i si t ed A l i c e, Fl o, and t he shor t -or der c ook ,
b ut w e’v e got good r eason f or r et ur ni ng (b ey ond t he f ood and gr eat
c onv er sat i on): t he di ner i s goi ng t o hel p us under st and t he
Command Pat t er n.

So, l et ’s t ak e a shor t det our b ac k t o t he di ner and st udy t he


i nt er ac t i ons b et w een t he c ust omer s, t he w ai t r ess, t he or der s, and
t he shor t -or der c ook . Thr ough t hese i nt er ac t i ons, y ou’r e goi ng t o
under st and t he ob jec t s i nv ol v ed i n t he Command Pat t er n and al so
get a f eel f or how t he dec oupl i ng w or k s. A f t er t hat , w e’r e goi ng t o
k noc k out t hat r emot e c ont r ol A PI.

Chec k i ng i n at t he Ob jec t v i l l e Di ner ...


Okay , we all know how the Diner operates:

Let’s study the interaction in a little more detail...


...and giv en this Diner is in Obj ectv ille, let’s think about the
obj ect and method calls inv olv ed, too!

The Objectville Diner roles and responsibilities


An Order Slip encapsulates a request to prepare a meal.

Think of the Order Slip as an obj ect that acts as a request to


prepare a meal. Li k e any ob jec t , i t c an b e passed ar ound—f r om t he
W ai t r ess t o t he or der c ount er , or t o t he nex t W ai t r ess t ak i ng ov er
her shi f t . It has an i nt er f ac e t hat c onsi st s of onl y one met hod,
or der U p(), t hat enc apsul at es t he ac t i ons needed t o pr epar e t he
meal . It al so has a r ef er enc e t o t he ob jec t t hat needs t o pr epar e i t
(i n our c ase, t he Shor t -Or der Cook ). It ’s enc apsul at ed i n t hat t he
W ai t r ess doesn’t hav e t o k now w hat ’s i n t he Or der or ev en w ho
pr epar es t he meal ; she onl y needs t o pass t he sl i p t hr ough t he or der
w i ndow and c al l “Or der up!”

The Waitress’s j ob is to take Order Slips and inv oke the


orderUp() method on them.

The Waitress has it easy : take an Order from the Customer,


continue helping customers until she makes it back to the order
counter, and then inv oke the orderUp() method to hav e the
meal prepared. A s w e’v e al r eady di sc ussed, i n Ob jec t v i l l e, t he
W ai t r ess r eal l y i sn’t w or r i ed ab out w hat ’s on t he Or der or w ho i s
goi ng t o pr epar e i t ; she just k now s Or der Sl i ps hav e an or der U p()
met hod she c an c al l t o get t he job done.
N ow , t hr oughout t he day , t he W ai t r ess’s t ak eOr der () met hod get s
par amet er i zed w i t h di f f er ent Or der Sl i ps f r om di f f er ent
c ust omer s, b ut t hat doesn’t f aze her ; she k now s al l Or der Sl i ps
suppor t t he or der U p() met hod and she c an c al l or der U p() any t i me
she needs a meal pr epar ed.

The Short-Order Cook has the knowledge required to prepare


the meal.

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.

Patience, we’re getting there...

Thi nk of t he Di ner as a model f or an OO desi gn pat t er n t hat al l ow s


us t o separ at e an ob jec t mak i ng a r equest f r om t he ob jec t s t hat
r ec ei v e and ex ec ut e t hose r equest s. For i nst anc e, i n our r emot e
c ont r ol A PI, w e need t o separ at e t he c ode t hat get s i nv ok ed w hen
w e pr ess a b ut t on f r om t he ob jec t s of t he v endor -spec i f i c c l asses
t hat c ar r y out t hose r equest s. W hat i f eac h sl ot of t he r emot e hel d
an ob jec t l i k e t he Di ner ’s Or der Sl i p ob jec t ? Then, w hen a b ut t on i s
pr essed, w e c oul d just c al l t he equi v al ent of t he or der U p() met hod
on t hi s ob jec t and hav e t he l i ght s t ur n on w i t hout t he r emot e
k now i ng t he det ai l s of how t o mak e t hose t hi ngs happen or w hat
ob jec t s ar e mak i ng t hem happen.

N ow , l et ’s sw i t c h gear s a b i t and map al l t hi s Di ner t al k t o t he


Command Pat t er n...
B R AIN PO W ER
Before we move on, spend some time studying the diagram two pages
back along with Diner roles and responsibilities until you think you’ve got a
handle on the Objectville Diner objects and relationships. Once you’ve
done that, get ready to nail the Command Pattern!

From the Diner to the Command Pattern


Ok ay , w e’v e spent enough t i me i n t he Ob jec t v i l l e Di ner t hat w e
k now al l t he per sonal i t i es and t hei r r esponsi b i l i t i es qui t e w el l .
N ow w e’r e goi ng t o r ew or k t he Di ner di agr am t o r ef l ec t t he
Command Pat t er n. You’l l see t hat al l t he pl ay er s ar e t he same; onl y
t he names hav e c hanged.
L O AD IN G T H E IN VO K ER

1. T he client creates a command object.

2. T he client does a setCommand() to store the command object


in the invoker.

3. Later...the client asks the invoker to execute the command.


Note: as you’ll see later in the chapter, once the command is
loaded into the invoker, it may be used and discarded, or it may
remain and be used many times.

W H O D O ES W H AT ?
Match the diner objects and methods with the corresponding names from
the Command Pattern.

Diner Command Pattern

Waitress Command

Short-Order Cook execute()

orderUp() Client

Order Invoker

Customer Receiver

takeOrder() setCommand()

Our first command object

Isn’t i t ab out t i me w e b ui l t our f i r st c ommand ob jec t ? Let ’s go ahead


and w r i t e some c ode f or t he r emot e c ont r ol . W hi l e w e hav en’t
f i gur ed out how t o desi gn t he r emot e c ont r ol A PI y et , b ui l di ng a
f ew t hi ngs f r om t he b ot t om up may hel p us...

I mplementing the Command interface

Fi r st t hi ngs f i r st : al l c ommand ob jec t s i mpl ement t he same


i nt er f ac e, w hi c h c onsi st s of one met hod. In t he Di ner w e c al l ed t hi s
met hod or der U p(); how ev er , w e t y pi c al l y just use t he name
ex ec ut e().

Her e’s t he Command i nt er f ac e:

I mplementing a command to turn a light on

N ow , l et ’s say y ou w ant t o i mpl ement a c ommand f or t ur ni ng a l i ght


on. Ref er r i ng t o our set of v endor c l asses, t he Li ght c l ass has t w o
met hods: on() and of f (). Her e’s how y ou c an i mpl ement t hi s as a
c ommand:
N ow t hat y ou’v e got a Li ght OnCommand c l ass, l et ’s see i f w e c an put
i t t o use...

Using the command object


Ok ay , l et ’s mak e t hi ngs si mpl e: say w e’v e got a r emot e c ont r ol w i t h
onl y one b ut t on and c or r espondi ng sl ot t o hol d a dev i c e t o c ont r ol :

Creating a simple test to use the Remote Control


Her e’s just a b i t of c ode t o t est out t he si mpl e r emot e c ont r ol . Let ’s
t ak e a l ook and w e’l l poi nt out how t he pi ec es mat c h t he Command
Pat t er n di agr am:
SH AR PEN YO U R PEN C IL
Okay, it’s time for you to implement the GarageDoorOpenCommand class.
First, supply the code for the class below. You’ll need the GarageDoor
class diagram.

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.)

public class RemoteControlTest {


public static void main(String[] args) {
SimpleRemoteControl remote = new
SimpleRemoteControl();
Light light = new Light();
GarageDoor garageDoor = new GarageDoor();
LightOnCommand lightOn = new
LightOnCommand(light);
GarageDoorOpenCommand garageOpen =
new GarageDoorOpenCommand(garageDoor);

remote.setCommand(lightOn);
remote.buttonWasPressed();
remote.setCommand(garageOpen);
remote.buttonWasPressed();
}
}

The Command Pattern defined


You’v e done y our t i me i n t he Ob jec t v i l l e Di ner , y ou’v e par t l y
i mpl ement ed t he r emot e c ont r ol A PI, and i n t he pr oc ess y ou’v e got
a f ai r l y good pi c t ur e of how t he c l asses and ob jec t s i nt er ac t i n t he
Command Pat t er n. N ow w e’r e goi ng t o def i ne t he Command Pat t er n
and nai l dow n al l t he det ai l s.

Let ’s st ar t w i t h i t s of f i c i al def i ni t i on:

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.

W e’v e al so seen a c oupl e ex ampl es of param eteriz ing an objec t w i t h


a c ommand. Bac k at t he di ner , t he W ai t r ess w as par amet er i zed w i t h
mul t i pl e or der s t hr oughout t he day . In t he si mpl e r emot e c ont r ol ,
w e f i r st l oaded t he b ut t on sl ot w i t h a “l i ght on” c ommand and t hen
l at er r epl ac ed i t w i t h a “gar age door open” c ommand. Li k e t he
W ai t r ess, y our r emot e sl ot di dn’t c ar e w hat c ommand ob jec t i t had,
as l ong as i t i mpl ement ed t he Command i nt er f ac e.

W hat w e hav en’t enc ount er ed y et i s usi ng c ommands t o i mpl ement


q ueues and logs and s upport undo operations . Don’t w or r y , t hose
ar e pr et t y st r ai ght f or w ar d ex t ensi ons of t he b asi c Command
Pat t er n, and w e’l l get t o t hem soon. W e c an al so easi l y suppor t
w hat ’s k now n as t he Met a Command Pat t er n onc e w e hav e t he b asi c s
i n pl ac e. The Met a Command Pat t er n al l ow s y ou t o c r eat e mac r os of
c ommands so t hat y ou c an ex ec ut e mul t i pl e c ommands at onc e.

The Command Pattern defined: the class diagram

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?

Sue: Li k e w e di d i n t he Si mpl eRemot e, w e need t o pr ov i de a w ay t o


assi gn c ommands t o sl ot s. In our c ase w e hav e sev en sl ot s, eac h w i t h
an on and of f b ut t on. So w e mi ght assi gn c ommands t o t he r emot e
somet hi ng l i k e t hi s:

onCommands[0] = onCommand;
offCommands[0] = offCommand;

and so on f or eac h of t he sev en c ommand sl ot s.

Mary : That mak es sense, ex c ept f or t he Li ght ob jec t s. How does t he


r emot e k now t he l i v i ng r oom f r om t he k i t c hen l i ght ?

Sue: A h, t hat ’s just i t —i t doesn’t ! The r emot e doesn’t k now any t hi ng


b ut how t o c al l ex ec ut e() on t he c or r espondi ng c ommand ob jec t
w hen a b ut t on i s pr essed.

Mary : Yeah, I sor t a got t hat , b ut i n t he i mpl ement at i on, how do w e


mak e sur e t he r i ght ob jec t s ar e t ur ni ng on and of f t he r i ght
dev i c es?

Sue: W hen w e c r eat e t he c ommands t o b e l oaded i nt o t he r emot e, w e


c r eat e one Li ght Command t hat i s b ound t o t he l i v i ng r oom l i ght
ob jec t and anot her t hat i s b ound t o t he k i t c hen l i ght ob jec t .
Rememb er , t he r ec ei v er of t he r equest get s b ound t o t he c ommand
i t ’s enc apsul at ed i n. So, b y t he t i me t he b ut t on i s pr essed, no one
c ar es w hi c h l i ght i s w hi c h; t he r i ght t hi ng just happens w hen t he
ex ec ut e() met hod i s c al l ed.

Mary : I t hi nk I’v e got i t . Let ’s i mpl ement t he r emot e and I t hi nk


t hi s w i l l get c l ear er !

Sue: Sounds good. Let ’s gi v e i t a shot ...

Assigning Commands to slots


So w e hav e a pl an: w e’r e goi ng t o assi gn a c ommand t o eac h sl ot i n
t he r emot e c ont r ol . Thi s mak es t he r emot e c ont r ol our inv ok er.
W hen a b ut t on i s pr essed, t he ex ec ut e() met hod w i l l b e c al l ed on
t he c or r espondi ng c ommand, w hi c h r esul t s i n ac t i ons b ei ng
i nv ok ed on t he r ec ei v er (l i k e l i ght s, c ei l i ng f ans, and st er eos).

Implementing the Remote Control


Implementing the Commands
W el l , w e’v e al r eady got t en our f eet w et i mpl ement i ng t he
Li ght OnCommand f or t he Si mpl eRemot eCont r ol . W e c an pl ug t hat
same c ode i n her e and ev er y t hi ng w or k s b eaut i f ul l y . Of f c ommands
ar e no di f f er ent ; i n f ac t , t he Li ght Of f Command l ook s l i k e t hi s:

Let ’s t r y somet hi ng a l i t t l e mor e c hal l engi ng; how ab out w r i t i ng on


and of f c ommands f or t he St er eo? Ok ay , of f i s easy , w e just b i nd t he
St er eo t o t he of f () met hod i n t he St er eoOf f Command. On i s a l i t t l e
mor e c ompl i c at ed; l et ’s say w e w ant t o w r i t e a
St er eoOnW i t hCDCommand...

N ot t oo b ad. Tak e a l ook at t he r est of t he v endor c l asses; b y now ,


y ou c an def i ni t el y k noc k out t he r est of t he Command c l asses w e
need f or t hose.

Putting the Remote Control through its paces


Our job w i t h t he r emot e i s pr et t y muc h done; al l w e need t o do i s
r un some t est s and get some doc ument at i on t oget her t o desc r i b e t he
A PI. Home A ut omat i on or Bust , Inc ., sur e i s goi ng t o b e i mpr essed,
don’t y a t hi nk ? W e’v e managed t o c ome up w i t h a desi gn t hat w i l l
al l ow t hem t o pr oduc e a r emot e t hat i s easy t o mai nt ai n, and t hey ’r e
goi ng t o hav e no t r oub l e c onv i nc i ng t he v endor s t o w r i t e some
si mpl e c ommand c l asses i n t he f ut ur e si nc e t hose ar e so easy t o
w r i t e.

Let ’s get t o t est i ng t hi s c ode!


Now, let’s check out the execution of our remote control test...

Good c at c h. W e di d sneak a l i t t l e somet hi ng i n t her e. In t he r emot e


c ont r ol , w e di dn’t w ant t o c hec k t o see i f a c ommand w as l oaded
ev er y t i me w e r ef er enc ed a sl ot . For i nst anc e, i n t he
onBut t onW asPushed() met hod, w e w oul d need c ode l i k e t hi s:

public void onButtonWasPushed(int slot) {


if (onCommands[slot] != null) {
onCommands[slot].execute();
}
}

So, how do w e get ar ound t hat ? Impl ement a c ommand t hat does
not hi ng!

public class NoCommand implements Command {


public void execute() { }
}

Then, i n our Remot eCont r ol c onst r uc t or , w e assi gn ev er y sl ot a


N oCommand ob jec t b y def aul t and w e k now w e’l l al w ay s hav e some
c ommand t o c al l i n eac h sl ot .

Command noCommand = new NoCommand();


for (int i = 0; i < 7; i++) {
onCommands[i] = noCommand;
offCommands[i] = noCommand;
}

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.

Time to write that documentation...


SER IO U S C O D IN G
Want to take your Command Pattern coding to the next level? You can use
Java’s lambda expressions to skip the step of creating all those concrete
command objects. With lambda expressions, instead of instantiating the
concrete command objects, you can use function objects in their place. In
other words, we can use a function object as a command. And, while we’re
at it, we can delete all those concrete Command classes, too.

Let’s take a look at how you’d use lambda expressions as commands to


simplify our previous code:

The updated code, using lambda expressions:

Once we’ve replaced the concrete commands with lambda expressions,


we can delete all those concrete command classes (LightOnCommand,
LightOffCommand, HottubOnCommand, HottubOffCommand, etc.). If you do
this for every concrete command, you’ll reduce the total number of classes
in the remote control application from 22 to 9.

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.

Whoops! We almost forgot...luckily , once we hav e our basic


Command classes, undo is easy to add. Let’s step through
adding undo to our commands and to the remote control...

What are we doing?


Ok ay , w e need t o add f unc t i onal i t y t o suppor t t he undo b ut t on on
t he r emot e. It w or k s l i k e t hi s: say t he Li v i ng Room Li ght i s of f and
y ou pr ess t he on b ut t on on t he r emot e. Ob v i ousl y t he l i ght t ur ns
on. N ow i f y ou pr ess t he undo b ut t on, t hen t he l ast ac t i on w i l l b e
r ev er sed—i n t hi s c ase, t he l i ght w i l l t ur n of f . Bef or e w e get i nt o
mor e c ompl ex ex ampl es, l et ’s get t he l i ght w or k i ng w i t h t he undo
b ut t on:

1 . When commands support undo, they hav e an undo()


method that mirrors the execute() method. Whatev er
execute() last did, undo() rev erses. So, before we can
add undo to our commands, we need to add an undo()
method to the Command interface:

That w as si mpl e enough.

N ow , l et ’s di v e i nt o t he Li ght c ommands and i mpl ement


t he undo() met hod.

2. Let ’s st ar t w i t h t he Li ght OnCommand: i f t he


Li ght OnCommand’s ex ec ut e() met hod w as c al l ed, t hen t he
on() met hod w as l ast c al l ed. W e k now t hat undo() needs t o
do t he opposi t e of t hi s b y c al l i ng t he of f () met hod.
Pi ec e of c ak e! N ow f or t he Li ght Of f Command. Her e t he
undo() met hod just needs t o c al l t he Li ght ’s on() met hod.

Coul d t hi s b e any easi er ? Ok ay , w e ar en’t done y et ; w e


need t o w or k a l i t t l e suppor t i nt o t he Remot e Cont r ol t o
handl e t r ac k i ng t he l ast b ut t on pr essed and t he undo
b ut t on pr ess.

3. To add suppor t f or t he undo b ut t on, w e onl y hav e t o mak e


a f ew smal l c hanges t o t he Remot e Cont r ol c l ass. Her e’s
how w e’r e goi ng t o do i t : w e’l l add a new i nst anc e v ar i ab l e
t o t r ac k t he l ast c ommand i nv ok ed; t hen, w henev er t he
undo b ut t on i s pr essed, w e r et r i ev e t hat c ommand and
i nv ok e i t s undo() met hod.

Time to QA that Undo button!


Ok ay , l et ’s r ew or k t he t est har ness a b i t t o t est t he undo b ut t on:

A nd her e ar e t he t est r esul t s...

Using state to implement Undo


Ok ay , i mpl ement i ng undo on t he Li ght w as i nst r uc t i v e b ut a l i t t l e
t oo easy . Ty pi c al l y , w e need t o manage a b i t of st at e t o i mpl ement
undo. Let ’s t r y somet hi ng a l i t t l e mor e i nt er est i ng, l i k e t he
Cei l i ngFan f r om t he v endor c l asses. The Cei l i ngFan c l ass al l ow s a
numb er of speeds t o b e set al ong w i t h an of f met hod.

Her e’s t he sour c e c ode f or t he Cei l i ngFan c l ass:


Adding Undo to the Ceiling Fan commands
N ow l et ’s t ac k l e addi ng undo t o t he v ar i ous Cei l i ng Fan c ommands.
To do so, w e need t o t r ac k t he l ast speed set t i ng of t he f an and, i f t he
undo() met hod i s c al l ed, r est or e t he f an t o i t s pr ev i ous set t i ng.
Her e’s t he c ode f or t he Cei l i ngFanHi ghCommand:
B R AIN PO W ER
We’ve got three more ceiling fan commands to write: low, medium, and off.
Can you see how these are implemented?

Get ready to test the ceiling fan


Ti me t o l oad up our r emot e c ont r ol w i t h t he c ei l i ng f an c ommands.
W e’r e goi ng t o l oad sl ot 0’s on b ut t on w i t h t he medi um set t i ng f or
t he f an and sl ot 1 w i t h t he hi gh set t i ng. Bot h c or r espondi ng of f
b ut t ons w i l l hol d t he c ei l i ng f an of f c ommand.

Her e’s our t est sc r i pt :

Testing the ceiling fan...


Ok ay , l et ’s f i r e up t he r emot e, l oad i t w i t h c ommands, and push some
b ut t ons!
Every remote needs a Party Mode!
What’s the point of hav ing a remote if y ou can’t push one button
and hav e the lights dimmed, the stereo and TV turned on, and
the hot tub fired up?
Using a macro command
Let ’s st ep t hr ough how w e use a mac r o c ommand:

1 . Fi r st w e c r eat e t he set of c ommands w e w ant t o go i nt o t he


mac r o:

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:

2. N ex t w e c r eat e t w o ar r ay s, one f or t he On c ommands and


one f or t he Of f c ommands, and l oad t hem w i t h t he
c or r espondi ng c ommands:

3. Then w e assi gn Mac r oCommand t o a b ut t on l i k e w e


al w ay s do:

4. Fi nal l y , w e just need t o push some b ut t ons and see i f t hi s


w or k s.
EXER C ISE
T he only thing our MacroCommand is missing is its undo functionality.
When the undo button is pressed after a macro command, all the
commands that were invoked in the macro must undo their previous
actions. Here’s the code for MacroCommand; go ahead and implement the
undo() method:

there are no Dumb Questions


Q: Do I alway s need a receiv er? Why can’t the command obj ect
implement the details of the execute() method?

A: In gener al , w e st r i v e f or “dumb ” c ommand ob jec t s t hat just


i nv ok e an ac t i on on a r ec ei v er ; how ev er , t her e ar e many ex ampl es
of “smar t ” c ommand ob jec t s t hat i mpl ement most , i f not al l , of t he
l ogi c needed t o c ar r y out a r equest . Cer t ai nl y y ou c an do t hi s; just
k eep i n mi nd y ou’l l no l onger hav e t he same l ev el of dec oupl i ng
b et w een t he i nv ok er and r ec ei v er , nor w i l l y ou b e ab l e t o
par amet er i ze y our c ommands w i t h r ec ei v er s.

Q: How can I implement a history of undo operations? I n other


words, I want to be able to press the undo button multiple
times.

A: Gr eat quest i on. It ’s pr et t y easy ac t ual l y ; i nst ead of k eepi ng just a


r ef er enc e t o t he l ast Command ex ec ut ed, y ou k eep a st ac k of
pr ev i ous c ommands. Then, w henev er undo i s pr essed, y our i nv ok er
pops t he f i r st i t em of f t he st ac k and c al l s i t s undo() met hod.

Q: Could I hav e j ust implemented party mode as a Command by


creating a Party Command and putting the calls to execute the
other Commands in Party Command’s execute() method?

A: You c oul d; how ev er , y ou’d essent i al l y b e “har dc odi ng” t he par t y


mode i nt o Par t y Command. W hy go t o t he t r oub l e? W i t h
Mac r oCommand, y ou c an dec i de dy nami c al l y w hi c h Commands y ou
w ant t o go i nt o Par t y Command, so y ou hav e mor e f l ex i b i l i t y usi ng
Mac r oCommands. In gener al , Mac r oCommand i s a mor e el egant
sol ut i on and r equi r es l ess new c ode.

More uses of the Command Pattern: queuing requests


Commands gi v e us a w ay t o pac k age a pi ec e of c omput at i on (a
r ec ei v er and a set of ac t i ons) and pass i t ar ound as a f i r st -c l ass
ob jec t . N ow , t he c omput at i on i t sel f may b e i nv ok ed l ong af t er some
c l i ent appl i c at i on c r eat es t he c ommand ob jec t . In f ac t , i t may ev en
b e i nv ok ed b y a di f f er ent t hr ead. W e c an t ak e t hi s sc enar i o and
appl y i t t o many usef ul appl i c at i ons, suc h as sc hedul er s, t hr ead
pool s, and job queues, t o name a f ew .

Imagi ne a job queue: y ou add c ommands t o t he queue on one end, and


on t he ot her end si t s a gr oup of t hr eads. Thr eads r un t he f ol l ow i ng
sc r i pt : t hey r emov e a c ommand f r om t he queue, c al l i t s ex ec ut e()
met hod, w ai t f or t he c al l t o f i ni sh, and t hen di sc ar d t he c ommand
ob jec t and r et r i ev e a new one.
N ot e t hat t he job queue c l asses ar e t ot al l y dec oupl ed f r om t he
ob jec t s t hat ar e doi ng t he c omput at i on. One mi nut e a t hr ead may b e
c omput i ng a f i nanc i al c omput at i on, and t he nex t i t may b e
r et r i ev i ng somet hi ng f r om t he net w or k . The job queue ob jec t s don’t
c ar e; t hey just r et r i ev e c ommands and c al l ex ec ut e(). Li k ew i se, as
l ong as y ou put ob jec t s i nt o t he queue t hat i mpl ement t he Command
Pat t er n, y our ex ec ut e() met hod w i l l b e i nv ok ed w hen a t hr ead i s
av ai l ab l e.

B R AIN PO W ER
How might a web server make use of such a queue? What other
applications can you think of?

More uses of the Command Pattern: logging requests


The semant i c s of some appl i c at i ons r equi r e t hat w e l og al l ac t i ons
and b e ab l e t o r ec ov er af t er a c r ash b y r ei nv ok i ng t hose ac t i ons.
The Command Pat t er n c an suppor t t hese semant i c s w i t h t he
addi t i on of t w o met hods: st or e() and l oad(). In Jav a w e c oul d use
ob jec t ser i al i zat i on t o i mpl ement t hese met hods, b ut t he nor mal
c av eat s f or usi ng ser i al i zat i on f or per si st enc e appl y .

How does t hi s w or k ? A s w e ex ec ut e c ommands, w e st or e a hi st or y of


t hem on di sk . W hen a c r ash oc c ur s, w e r el oad t he c ommand ob jec t s
and i nv ok e t hei r ex ec ut e() met hods i n b at c h and i n or der .

N ow , t hi s k i nd of l oggi ng w oul dn’t mak e sense f or a r emot e c ont r ol ;


how ev er , t her e ar e many appl i c at i ons t hat i nv ok e ac t i ons on l ar ge
dat a st r uc t ur es t hat c an’t b e qui c k l y sav ed eac h t i me a c hange i s
made. By usi ng l oggi ng, w e c an sav e al l t he oper at i ons si nc e t he l ast
c hec k poi nt , and i f t her e i s a sy st em f ai l ur e, appl y t hose oper at i ons
t o our c hec k poi nt . Tak e, f or ex ampl e, a spr eadsheet appl i c at i on: w e
mi ght w ant t o i mpl ement our f ai l ur e r ec ov er y b y l oggi ng t he
ac t i ons on t he spr eadsheet r at her t han w r i t i ng a c opy of t he
spr eadsheet t o di sk ev er y t i me a c hange oc c ur s. In mor e adv anc ed
appl i c at i ons, t hese t ec hni ques c an b e ex t ended t o appl y t o set s of
oper at i ons i n a t r ansac t i onal manner so t hat al l of t he oper at i ons
c ompl et e, or none of t hem do.
Command Pattern in the Real World
Rememb er t he l i t t l e l i f e-c hangi ng appl i c at i on f r om Chapt er 2?

In t hat c hapt er w e saw how Jav a’s Sw i ng l i b r ar y i s c hoc k f ul l of


Ob ser v er s i n t he f or m of A c t i onLi st ener s t hat l i st en i n (or obs erv e)
ev ent s on user i nt er f ac e c omponent s.

W el l , i t t ur ns out t hat A c t i onLi st ener i s not just an Ob ser v er


i nt er f ac e, i t ’s al so a Command i nt er f ac e, and our A ngel Li st ener and
Dev i l Li st ener c l asses ar e not just Ob ser v er s, b ut al so c onc r et e
Commands. That ’s r i ght , w e hav e t w o pat t er ns i n one ex ampl e!

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.

public class SwingObserverExample {


// Set up ...
JButton button = new JButton("Should I do
it?");
button.addActionListener(new AngelListener());
button.addActionListener(new DevilListener());
// Set frame properties here
}
class AngelListener implements ActionListener {
public void actionPerformed(ActionEvent event)
{
System.out.println("Don't do it, you might
regret it!");
}
}
class DevilListener implements ActionListener {
public void actionPerformed(ActionEvent event)
{
System.out.println("Come on, do it!");
}
}
}

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.

Here’s our solution.


Tools for your Design Toolbox
Your t ool b ox i s st ar t i ng t o get heav y ! In t hi s c hapt er w e’v e added a
pat t er n t hat al l ow s us t o enc apsul at e met hods i nt o Command
ob jec t s: st or e t hem, pass t hem ar ound, and i nv ok e t hem w hen y ou
need t hem.

B U L L ET PO IN T S

T he Command Pattern decouples an object making a request


from the one that knows how to perform it.

A Command object is at the center of this decoupling and


encapsulates a receiver with an action (or set of actions).

An invoker makes a request of a Command object by calling its


execute() method, which invokes those actions on the receiver.

Invokers can be parameterized with Commands, even


dynamically at runtime.

Commands may support undo by implementing an undo()


method that restores the object to its previous state before the
execute() method was last called.

MacroCommands are a simple extension of the Command


Pattern that allow multiple commands to be invoked. Likewise,
MacroCommands can easily support undo().

In practice, it’s not uncommon for “smart” Command objects to


implement the request themselves rather than delegating to a
receiver.

Commands may also be used to implement logging and


transactional systems.

Design Patterns Crossword


Ti me t o t ak e a b r eat her and l et i t al l si nk i n.

It ’s anot her c r ossw or d; al l of t he sol ut i on w or ds ar e f r om t hi s


c hapt er .

ACROSS
5. Our f av or i t e c i t y .

6. Company t hat got us w or d-of -mout h b usi ness.

7 . Rol e of c ust omer i n t he Command Pat t er n.

9. Ob jec t t hat k now s t he ac t i ons and t he r ec ei v er .

1 2. Inv ok er and r ec ei v er ar e _________.

1 5. The W ai t r ess w as one.

1 6. Dr . Seuss di ner f ood (f our w or ds).

1 7 . A not her t hi ng Command c an do.

DOWN

1 . The Cook and t hi s per son w er e def i ni t el y dec oupl ed.

2. The W ai t r ess di dn’t do t hi s.

3. A c ommand enc apsul at es t hi s.

4. A c t as t he r ec ei v er s i n t he r emot e c ont r ol (t w o w or ds).

8. Ob jec t t hat k now s how t o get t hi ngs done.

1 0. Car r i es out a r equest .

1 1 . A l l c ommands pr ov i de t hi s.

1 3. Our f i r st c ommand ob jec t c ont r ol l ed t hi s.

1 4. A c ommand __________ a set of ac t i ons and a r ec ei v er .

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.

public class GarageDoorOpenCommand implements Command


{
GarageDoor garageDoor;

public GarageDoorOpenCommand(GarageDoor garageDoor)


{
this.garageDoor = garageDoor;
}
public void execute() {
garageDoor.up();
}
}

Here’s the output:

EXER C ISE SO L U T IO N
Here is the undo() method for the MacroCommand.

public class MacroCommand implements Command {


Command[] commands;
public MacroCommand(Command[] commands) {
this.commands = commands;
}
public void execute() {
for (int i = 0; i < commands.length; i++) {
commands[i].execute();
}
}
public void undo() {
for (int i = commands.length - 1; i > = 0; i--
) {
commands[i].undo();
}
}
}
SH AR PEN YO U R PEN C IL
SO L U T IO N
Here’s the code to create commands for the off button.

LightOffCommand lightOff = new LightOffCommand(light);


StereoOffCommand stereoOff = new
StereoOffCommand(stereo);
TVOffCommand tvOff = new TVOffCommand(tv);
HottubOffCommand hottubOff = new
HottubOffCommand(hottub);
Chapter 7. Being Adaptive: The
Adapter and Facade Patterns

I n this chapter we’re going to attempt such impossible feats as


putting a square peg in a round hole. Sound i mpossi b l e? N ot w hen
w e hav e Desi gn Pat t er ns. Rememb er t he Dec or at or Pat t er n? W e
wrapped obj ects t o gi v e t hem new r esponsi b i l i t i es. N ow w e’r e
goi ng t o w r ap some ob jec t s w i t h a di f f er ent pur pose: t o mak e t hei r
i nt er f ac es l ook l i k e somet hi ng t hey ’r e not . W hy w oul d w e do t hat ?
So w e c an adapt a desi gn ex pec t i ng one i nt er f ac e t o a c l ass t hat
i mpl ement s a di f f er ent i nt er f ac e. That ’s not al l ; w hi l e w e’r e at i t ,
w e’r e goi ng t o l ook at anot her pat t er n t hat w r aps ob jec t s t o
si mpl i f y t hei r i nt er f ac e.

Adapters all around us


Y ou’ll hav e no trouble understanding what an OO adapter is
because the real world is full of them. How’s this for an example:
Hav e y ou ev er needed to use a US-made laptop in Great
Britain? Then y ou’v e probably needed an AC power adapter...

You k now w hat t he adapt er does: i t si t s i n b et w een t he pl ug of y our


l apt op and t he Br i t i sh A C out l et ; i t s job i s t o adapt t he Br i t i sh
out l et so t hat y ou c an pl ug y our l apt op i nt o i t and r ec ei v e pow er .
Or l ook at i t t hi s w ay : t he adapt er c hanges t he i nt er f ac e of t he
out l et i nt o one t hat y our l apt op ex pec t s.

N O TE
How many other real-world adapters can you think of?

Some A C adapt er s ar e si mpl e—t hey onl y c hange t he shape of t he


out l et so t hat i t mat c hes y our pl ug, and t hey pass t he A C c ur r ent
st r ai ght t hr ough—b ut ot her adapt er s ar e mor e c ompl ex i nt er nal l y
and may need t o st ep t he pow er up or dow n t o mat c h y our dev i c es’
needs.

Ok ay , t hat ’s t he r eal w or l d; w hat ab out ob jec t -or i ent ed adapt er s?


W el l , our OO adapt er s pl ay t he same r ol e as t hei r r eal -w or l d
c ount er par t s: t hey t ak e an i nt er f ac e and adapt i t t o one t hat a
c l i ent i s ex pec t i ng.

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.

The adapt er ac t s as t he mi ddl eman b y r ec ei v i ng r equest s f r om t he


c l i ent and c onv er t i ng t hem i nt o r equest s t hat mak e sense on t he
v endor c l asses.

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?

If it walks like a duck and quacks like a duck, then it


must might be a duck turkey wrapped with a duck
adapter...

It ’s t i me t o see an adapt er i n ac t i on. Rememb er our duc k s f r om


Chapt er 1 ? Let ’s r ev i ew a sl i ght l y si mpl i f i ed v er si on of t he Duc k
i nt er f ac es and c l asses:

Her e’s a sub c l ass of Duc k , t he Mal l ar dDuc k :

N ow i t ’s t i me t o meet t he new est f ow l on t he b l oc k :


N ow , l et ’s say y ou’r e shor t on Duc k ob jec t s and y ou’d l i k e t o use
some Tur k ey ob jec t s i n t hei r pl ac e. Ob v i ousl y w e c an’t use t he
t ur k ey s out r i ght b ec ause t hey hav e a di f f er ent i nt er f ac e.

So, l et ’s w r i t e an A dapt er :

C O D E U P C L O SE

Test drive the adapter


N ow w e just need some c ode t o t est dr i v e our adapt er :

The Adapter Pattern explained


N ow t hat w e hav e an i dea of w hat an A dapt er i s, l et ’s st ep b ac k and
l ook at al l t he pi ec es agai n.

Here’s how the Client uses the Adapter

1 . The c l i ent mak es a r equest t o t he adapt er b y c al l i ng a


met hod on i t usi ng t he t ar get i nt er f ac e.

2. The adapt er t r ansl at es t he r equest i nt o one or mor e c al l s


on t he adapt ee usi ng t he adapt ee i nt er f ac e.

3. The c l i ent r ec ei v es t he r esul t s of t he c al l and nev er


k now s t her e i s an adapt er doi ng t he t r ansl at i on.
N O TE
Note that the Client and Adaptee are decoupled—neither
knows about the other.

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?

there are no Dumb Questions


Q: How much “adapting” does an adapter need to do? I t seems
like if I need to implement a large target interface, I could hav e
a LOT of work on my hands.

A: You c er t ai nl y c oul d. The job of i mpl ement i ng an adapt er r eal l y


i s pr opor t i onal t o t he si ze of t he i nt er f ac e y ou need t o suppor t as
y our t ar get i nt er f ac e. Thi nk ab out y our opt i ons, how ev er . You
c oul d r ew or k al l y our c l i ent -si de c al l s t o t he i nt er f ac e, w hi c h
w oul d r esul t i n a l ot of i nv est i gat i v e w or k and c ode c hanges. Or ,
y ou c an c l eanl y pr ov i de one c l ass t hat enc apsul at es al l t he c hanges
i n t hat c l ass.

Q: Does an adapter alway s wrap one and only one class?

A: The A dapt er Pat t er n’s r ol e i s t o c onv er t one i nt er f ac e i nt o


anot her . W hi l e most ex ampl es of t he A dapt er Pat t er n show an
adapt er w r appi ng one adapt ee, w e b ot h k now t he w or l d i s of t en a
b i t mor e messy . So, y ou may w el l hav e si t uat i ons w her e an adapt er
hol ds t w o or mor e adapt ees t hat ar e needed t o i mpl ement t he t ar get
i nt er f ac e.

Thi s r el at es t o anot her pat t er n c al l ed t he Fac ade Pat t er n; peopl e


of t en c onf use t he t w o. Remi nd us t o r ev i si t t hi s poi nt w hen w e t al k
ab out f ac ades l at er i n t hi s c hapt er .

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?

A: N ot nec essar i l y . One t hi ng y ou c an do i s c r eat e a Tw o W ay


A dapt er t hat suppor t s b ot h i nt er f ac es. To c r eat e a Tw o W ay
A dapt er , just i mpl ement b ot h i nt er f ac es i nv ol v ed, so t he adapt er
c an ac t as an ol d i nt er f ac e or a new i nt er f ac e.

Adapter Pattern defined


Enough duc k s, t ur k ey s, and A C pow er adapt er s; l et ’s get r eal and
l ook at t he of f i c i al def i ni t i on of t he A dapt er Pat t er n:

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.

N ow , w e k now t hi s pat t er n al l ow s us t o use a c l i ent w i t h an


i nc ompat i b l e i nt er f ac e b y c r eat i ng an A dapt er t hat does t he
c onv er si on. Thi s ac t s t o dec oupl e t he c l i ent f r om t he i mpl ement ed
i nt er f ac e, and i f w e ex pec t t he i nt er f ac e t o c hange ov er t i me, t he
adapt er enc apsul at es t hat c hange so t hat t he c l i ent doesn’t hav e t o
b e modi f i ed eac h t i me i t needs t o oper at e agai nst a di f f er ent
i nt er f ac e.

W e’v e t ak en a l ook at t he r unt i me b ehav i or of t he pat t er n; l et ’s


t ak e a l ook at i t s c l ass di agr am as w el l :

The A dapt er Pat t er n i s f ul l of good ob jec t -or i ent ed desi gn


pr i nc i pl es: c hec k out t he use of ob jec t c omposi t i on t o w r ap t he
adapt ee w i t h an al t er ed i nt er f ac e. Thi s appr oac h has t he added
adv ant age t hat w e c an use an adapt er w i t h any sub c l ass of t he
adapt ee.

A l so c hec k out how t he pat t er n b i nds t he c l i ent t o an i nt er f ac e, not


an i mpl ement at i on; w e c oul d use sev er al adapt er s, eac h c onv er t i ng
a di f f er ent b ac k end set of c l asses. Or , w e c oul d add new
i mpl ement at i ons af t er t he f ac t , as l ong as t hey adher e t o t he Tar get
i nt er f ac e.

Object and class adapters


N ow despi t e hav i ng def i ned t he pat t er n, w e hav en’t t ol d y ou t he
w hol e st or y y et . Ther e ar e ac t ual l y tw o k i nds of adapt er s: objec t
adapt er s and c las s adapt er s. Thi s c hapt er has c ov er ed ob jec t
adapt er s, and t he c l ass di agr am on t he pr ev i ous page i s a di agr am of
an ob jec t adapt er .

So w hat ’s a c las s adapt er and w hy hav en’t w e t ol d y ou ab out i t ?


Bec ause y ou need mul t i pl e i nher i t anc e t o i mpl ement i t , w hi c h
i sn’t possi b l e i n Jav a. But t hat doesn’t mean y ou mi ght not
enc ount er a need f or c l ass adapt er s dow n t he r oad w hen usi ng y our
f av or i t e mul t i pl e i nher i t anc e l anguage! Let ’s l ook at t he c l ass
di agr am f or mul t i pl e i nher i t anc e.

Look f ami l i ar ? That ’s r i ght —t he onl y di f f er enc e i s t hat w i t h a c l ass


adapt er w e sub c l ass t he Tar get and t he A dapt ee, w hi l e w i t h an
ob jec t adapt er w e use c omposi t i on t o pass r equest s t o an A dapt ee.

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

Your job i s t o t ak e t he duc k and t ur k ey magnet s and dr ag t hem ov er


t he par t of t he di agr am t hat desc r i b es t he r ol e pl ay ed b y t hat b i r d,
i n our ear l i er ex ampl e. (Tr y not t o f l i p b ac k t hr ough t he pages.)
Then add y our ow n annot at i ons t o desc r i b e how i t w or k s.

Class Adapter

Obj ect 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

Obj ect Adapter

Toni ght ’s t al k : Obj ect Adapter and Class Adapter meet face to
face.
Object Adapter: Class Adapter:

Because I use composition I’ve got


a leg up. I can adapt not only an
adaptee class, but any of its
subclasses.

That’s true, I do have trouble with that because I


am committed to one specific adaptee class, but I
have a huge advantage because I don’t have to
reimplement my entire adaptee. I can also
override the behavior of my adaptee if I need to
because I’m just subclassing.

In my part of the world, we like to


use composition over inheritance;
you may be saving a few lines of
code, but all I’m doing is writing a
little code to delegate to the adaptee.
We like to keep things flexible.

Flexible maybe, but efficient? No. There is just


one of me, not an adapter and an adaptee.

You’re worried about one little


object? You might be able to quickly
override a method, but any
behavior I add to my adapter code
works with my adaptee class and
all its subclasses.

Yeah, but what if a subclass of Adaptee adds


some new behavior—then what?

Hey, come on, cut me some slack, I


just need to compose with the
subclass to make that work.

Sounds messy...

You wanna see messy? Look in the


mirror!

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

If y ou’v e b een ar ound Jav a f or a w hi l e, y ou pr ob ab l y r ememb er


t hat t he ear l y c ol l ec t i on t y pes (V ec t or , St ac k , Hasht ab l e, and a f ew
ot her s) i mpl ement a met hod, el ement s(), w hi c h r et ur ns an
Enumer at i on. The Enumer at i on i nt er f ac e al l ow s y ou t o st ep
t hr ough t he el ement s of a c ol l ec t i on w i t hout k now i ng t he spec i f i c s
of how t hey ar e managed i n t he c ol l ec t i on.

Iterators

The mor e r ec ent Col l ec t i on c l asses use an It er at or i nt er f ac e t hat ,


l i k e t he Enumer at i on i nt er f ac e, al l ow s y ou t o i t er at e t hr ough a set
of i t ems i n a c ol l ec t i on, and adds t he ab i l i t y t o r emov e i t ems.

Using Enumerators with code that expects Iterators


W e ar e somet i mes f ac ed w i t h l egac y c ode t hat ex poses t he
Enumer at i on i nt er f ac e, y et w e’d l i k e f or our new c ode t o use onl y
It er at or s. It l ook s l i k e w e need t o b ui l d an adapt er .

Adapting an Enumeration to an Iterator


Fi r st w e’l l l ook at t he t w o i nt er f ac es t o f i gur e out how t he met hods
map f r om one t o t he ot her . In ot her w or ds, w e’l l f i gur e out w hat t o
c al l on t he adapt ee w hen t he c l i ent i nv ok es a met hod on t he t ar get .
Designing the Adapter

Her e’s w hat t he c l asses shoul d l ook l i k e: w e need an adapt er t hat


i mpl ement s t he Tar get i nt er f ac e and i s c omposed w i t h an adapt ee.
The hasN ex t () and nex t () met hods ar e goi ng t o b e st r ai ght f or w ar d t o
map f r om t ar get t o adapt ee: w e just pass t hem r i ght t hr ough. But
w hat do y ou do ab out r emov e()? Thi nk ab out i t f or a moment (and
w e’l l deal w i t h i t on t he nex t page). For now , her e’s t he c l ass
di agr am:

Dealing with the remove() method

W el l , w e k now Enumer at i on doesn’t suppor t r emov e(). It ’s a “r ead


onl y ” i nt er f ac e. Ther e’s no w ay t o i mpl ement a f ul l y f unc t i oni ng
r emov e() met hod on t he adapt er . The b est w e c an do i s t hr ow a
r unt i me ex c ept i on. Luc k i l y , t he desi gner s of t he It er at or i nt er f ac e
f or esaw t hi s need and def i ned t he r emov e() met hod so t hat i t
suppor t s an U nsuppor t edOper at i onEx c ept i on.

Thi s i s a c ase w her e t he adapt er i sn’t per f ec t ; c l i ent s w i l l hav e t o


w at c h out f or pot ent i al ex c ept i ons, b ut as l ong as t he c l i ent i s
c ar ef ul and t he adapt er i s w el l doc ument ed, t hi s i s a per f ec t l y
r easonab l e sol ut i on.

Writing the EnumerationIterator adapter

Her e’s si mpl e b ut ef f ec t i v e c ode f or al l t hose l egac y c l asses st i l l


pr oduc i ng Enumer at i ons:

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.

Write an Adapter that adapts an Iterator to an Enumeration. You can test


your code by adapting an ArrayList. T he ArrayList class supports the
Iterator interface but doesn’t support Enumerations.

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:

I’m important. My job is all about responsibility—


you know that when a Decorator is involved, there’s
going to be some new responsibilities or behaviors
added to your design.

You decorators want all the


glory while us adapters are
down in the trenches doing the
dirty work: converting interfaces.
Our jobs may not be glamorous,
but our clients sure do
appreciate us making their lives
simpler.

That may be true, but don’t think we don’t work


hard. When we have to decorate a big interface,
whoa, that can take a lot of code.

Try being an adapter when


you’ve got to bring several
classes together to provide the
interface your client is expecting.
Now that’s tough. But we have a
saying: “A decoupled client is a
happy client.”

Cute. Don’t think we get all the glory; sometimes I’m


just one decorator that is being wrapped by who
knows how many other decorators. When a method
call gets delegated to you, you have no idea how
many other decorators have already dealt with it
and you don’t know that you’ll ever get noticed for
your efforts servicing the request.

Hey, if adapters are doing their


job, our clients never even know
we’re there. It can be a thankless
job.

But the great thing about us


adapters is that we allow clients
to make use of new libraries and
subsets without changing any
code; they just rely on us to do
the conversion for them. Hey, it’s
a niche, but we’re good at it.

Well, us decorators do that as well, only we allow


new behavior to be added to classes without
altering existing code. I still say that adapters are
just fancy decorators—I mean, just like us, you wrap
an object.

No, no, no, not at all. We


always convert the interface of
what we wrap; you never do. I’d
say a decorator is like an
adapter; it’s just that you don’t
change the interface!

Uh, no. Our job in life is to extend the behaviors or


responsibilities of the objects we wrap; we aren’t a
simple pass through.

Hey, who are you calling a


simple pass through? Come on
down and we’ll see how long
you last converting a few
interfaces!

Maybe we should agree to disagree. We seem to


look somewhat similar on paper, but clearly we are
miles apart in our intent.

Oh yeah, I’m with you there.

And now for something different...


There’s another pattern in this chapter.

You’v e seen how t he A dapt er Pat t er n c onv er t s t he i nt er f ac e of a


c l ass i nt o one t hat a c l i ent i s ex pec t i ng. You al so k now w e ac hi ev e
t hi s i n Jav a b y w r appi ng t he ob jec t t hat has an i nc ompat i b l e
i nt er f ac e w i t h an ob jec t t hat i mpl ement s t he c or r ec t one.

W e’r e goi ng t o l ook at a pat t er n now t hat al t er s an i nt er f ac e, b ut


f or a di f f er ent r eason: t o si mpl i f y t he i nt er f ac e. It ’s apt l y named
t he Fac ade Pat t er n b ec ause t hi s pat t er n hi des al l t he c ompl ex i t y of
one or mor e c l asses b ehi nd a c l ean, w el l -l i t f ac ade.

W H O D O ES W H AT ?
Match each pattern with its intent:

Pattern Intent

Decorator Converts one interface to another

Adapter Doesn’t alter the interface, but adds responsibility

Facade Makes an interface simpler

Home Sweet Home Theater


Bef or e w e di v e i nt o t he det ai l s of t he Fac ade Pat t er n, l et ’s t ak e a
l ook at a gr ow i ng nat i onal ob sessi on: b ui l di ng a ni c e t heat er t o
b i nge-w at c h al l t hose mov i es and TV ser i es.

You’v e done y our r esear c h and y ou’v e assemb l ed a k i l l er sy st em


c ompl et e w i t h a st r eami ng pl ay er , a pr ojec t i on v i deo sy st em, an
aut omat ed sc r een, sur r ound sound, and ev en a popc or n popper .

Chec k out al l t he c omponent s y ou’v e put t oget her :

You’v e spent w eek s r unni ng w i r e, mount i ng t he pr ojec t or , mak i ng


al l t he c onnec t i ons, and f i ne t uni ng. N ow i t ’s t i me t o put i t al l i n
mot i on and enjoy a mov i e...

Watching a movie (the hard way)


Pick out a mov ie, relax, and get ready for mov ie magic. Oh,
there’s j ust one thing—to watch the mov ie, y ou need to perform
a few tasks:

1 . Turn on the popcorn popper

2. Start the popper popping

3. Dim the lights

4. Put the screen down

5. Turn the proj ector on

6. Set the proj ector input to streaming play er

7 . Put the proj ector on widescreen mode

8. Turn the sound amplifier on

9. Set the amplifier to streaming play er input

1 0. Set the amplifier to surround sound

1 1 . Set the amplifier v olume to medium (5)

1 2. Turn the streaming play er on

1 3. Start play ing the mov ie

Let’s check out those same tasks in terms of the classes and the
method calls needed to perform them:
But there’s more...

W hen t he mov i e i s ov er , how do y ou t ur n ev er y t hi ng of f ?


W oul dn’t y ou hav e t o do al l of t hi s ov er agai n, i n r ev er se?

W oul dn’t i t b e as c ompl ex t o l i st en t o t he r adi o?

If y ou dec i de t o upgr ade y our sy st em, y ou’r e pr ob ab l y


goi ng t o hav e t o l ear n a sl i ght l y di f f er ent pr oc edur e.

So w hat t o do? The c ompl ex i t y of usi ng y our home t heat er i s


b ec omi ng appar ent !

Let ’s see how t he Fac ade Pat t er n c an get us out of t hi s mess so w e c an


enjoy t he mov i e...

Lights, Camera, Facade!


A Fac ade i s just w hat y ou need: w i t h t he Fac ade Pat t er n y ou c an
t ak e a c ompl ex sub sy st em and mak e i t easi er t o use b y
i mpl ement i ng a Fac ade c l ass t hat pr ov i des one, mor e r easonab l e
i nt er f ac e. Don’t w or r y ; i f y ou need t he pow er of t he c ompl ex
sub sy st em, i t ’s st i l l t her e f or y ou t o use, b ut i f al l y ou need i s a
st r ai ght f or w ar d i nt er f ac e, t he Fac ade i s t her e f or y ou.

Let ’s t ak e a l ook at how t he Fac ade oper at es:

there are no Dumb Questions


Q: I f the facade encapsulates the subsy stem classes, how does
a client that needs lower-lev el functionality gain access to
them?

A: Fac ades don’t “enc apsul at e” t he sub sy st em c l asses; t hey mer el y


pr ov i de a si mpl i f i ed i nt er f ac e t o t hei r f unc t i onal i t y . The
sub sy st em c l asses st i l l r emai n av ai l ab l e f or di r ec t use b y c l i ent s
t hat need t o use mor e spec i f i c i nt er f ac es. Thi s i s a ni c e pr oper t y of
t he Fac ade Pat t er n: i t pr ov i des a si mpl i f i ed i nt er f ac e w hi l e st i l l
ex posi ng t he f ul l f unc t i onal i t y of t he sy st em t o t hose w ho may
need i t .

Q: Does the facade add any functionality or does it j ust pass


through each request to the subsy stem?

A: A f ac ade i s f r ee t o add i t s ow n “smar t s” i n addi t i on t o mak i ng use


of t he sub sy st em. For i nst anc e, w hi l e our home t heat er f ac ade
doesn’t i mpl ement any new b ehav i or , i t i s smar t enough t o k now
t hat t he popc or n popper has t o b e t ur ned on b ef or e i t c an pop (as
w el l as t he det ai l s of how t o t ur n on and st age a mov i e show i ng).

Q: Does each subsy stem hav e only one facade?

A: N ot nec essar i l y . The pat t er n c er t ai nl y al l ow s f or any numb er of


f ac ades t o b e c r eat ed f or a gi v en sub sy st em.

Q: What is the benefit of the facade other than the fact that I
now hav e a simpler interface?

A: The Fac ade Pat t er n al so al l ow s y ou t o dec oupl e y our c l i ent


i mpl ement at i on f r om any one sub sy st em. Let ’s say t hat y ou get a b i g
r ai se and dec i de t o upgr ade y our home t heat er t o al l new
c omponent s t hat hav e di f f er ent i nt er f ac es. W el l , i f y ou c oded y our
c l i ent t o t he f ac ade r at her t han t he sub sy st em, y our c l i ent c ode
doesn’t need t o c hange, just t he f ac ade (and hopef ul l y t he
manuf ac t ur er i s suppl y i ng t hat !).

Q: So the way to tell the difference between the Adapter Pattern


and the F acade Pattern is that the adapter wraps one class and
the facade may represent many classes?

A: N o! Rememb er , t he A dapt er Pat t er n c hanges t he i nt er f ac e of one


or mor e c l asses i nt o one i nt er f ac e t hat a c l i ent i s ex pec t i ng. W hi l e
most t ex t b ook ex ampl es show t he adapt er adapt i ng one c l ass, y ou
may need t o adapt many c l asses t o pr ov i de t he i nt er f ac e a c l i ent i s
c oded t o. Li k ew i se, a Fac ade may pr ov i de a si mpl i f i ed i nt er f ac e t o a
si ngl e c l ass w i t h a v er y c ompl ex i nt er f ac e.

The di f f er enc e b et w een t he t w o i s not i n t er ms of how many c l asses


t hey “w r ap,” i t i s i n t hei r i nt ent . The i nt ent of t he A dapt er Pat t er n
i s t o al t er an i nt er f ac e so t hat i t mat c hes one a c l i ent i s ex pec t i ng.
The i nt ent of t he Fac ade Pat t er n i s t o pr ov i de a si mpl i f i ed
i nt er f ac e t o a sub sy st em.

A fa ca d e no t o nly s im p lifie s a n inte rfa ce , it d e co up le s


a clie nt fro m a s ub s y s te m o f co m p o ne nts .

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.

Constructing your home theater facade


Let ’s st ep t hr ough t he c onst r uc t i on of t he HomeTheat er Fac ade
c l ass. The f i r st st ep i s t o use c omposi t i on so t hat t he f ac ade has
ac c ess t o al l t he c omponent s of t he sub sy st em:

Implementing the simplified interface


N ow i t ’s t i me t o b r i ng t he c omponent s of t he sub sy st em t oget her
i nt o a uni f i ed i nt er f ac e. Let ’s i mpl ement t he w at c hMov i e() and
endMov i e() met hods:

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?

Time to watch a movie (the easy way)

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.

Bef or e w e i nt r oduc e t hat new pr i nc i pl e, l et ’s t ak e a l ook at t he


of f i c i al def i ni t i on of t he pat t er n:

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.

Ther e i sn’t a l ot her e t hat y ou don’t al r eady k now , b ut one of t he


most i mpor t ant t hi ngs t o r ememb er ab out a pat t er n i s i t s i nt ent .
Thi s def i ni t i on t el l s us l oud and c l ear t hat t he pur pose of t he
f ac ade i s t o mak e a sub sy st em easi er t o use t hr ough a si mpl i f i ed
i nt er f ac e. You c an see t hi s i n t he pat t er n’s c l ass di agr am:

That ’s i t ; y ou’v e got anot her pat t er n under y our b el t ! N ow , i t ’s t i me


f or t hat new OO pr i nc i pl e. W at c h out , t hi s one c an c hal l enge some
assumpt i ons!

The Principle of Least Knowledge


The Pr i nc i pl e of Least Know l edge gui des us t o r educ e t he
i nt er ac t i ons b et w een ob jec t s t o just a f ew c l ose “f r i ends.” The
pr i nc i pl e i s usual l y st at ed as:

But w hat does t hi s mean i n r eal t er ms? It means w hen y ou ar e


desi gni ng a sy st em, f or any ob jec t , b e c ar ef ul of t he numb er of
c l asses i t i nt er ac t s w i t h and al so how i t c omes t o i nt er ac t w i t h
t hose c l asses.

Thi s pr i nc i pl e pr ev ent s us f r om c r eat i ng desi gns t hat hav e a l ar ge


numb er of c l asses c oupl ed t oget her so t hat c hanges i n one par t of
t he sy st em c asc ade t o ot her par t s. W hen y ou b ui l d a l ot of
dependenc i es b et w een many c l asses, y ou ar e b ui l di ng a f r agi l e
sy st em t hat w i l l b e c ost l y t o mai nt ai n and c ompl ex f or ot her s t o
under st and.
B R AIN PO W ER
How many classes is this code coupled to?

public float getTemp() {


return station.getThermometer().getTemperature();
}

How NOT to Win Friends and Influence Objects


Ok ay , b ut how do y ou k eep f r om doi ng t hi s? The pr i nc i pl e pr ov i des
some gui del i nes: t ak e any ob jec t , and f r om any met hod i n t hat
ob jec t , i nv ok e onl y met hods t hat b el ong t o:

Thi s sounds k i nd of st r i ngent , doesn’t i t ? W hat ’s t he har m i n c al l i ng


t he met hod of an ob jec t w e get b ac k f r om anot her c al l ? W el l , i f w e
w er e t o do t hat , t hen w e’d b e mak i ng a r equest of anot her ob jec t ’s
sub par t (and i nc r easi ng t he numb er of ob jec t s w e di r ec t l y k now ).
In suc h c ases, t he pr i nc i pl e f or c es us t o ask t he ob jec t t o mak e t he
r equest f or us; t hat w ay , w e don’t hav e t o k now ab out i t s c omponent
ob jec t s (and w e k eep our c i r c l e of f r i ends smal l ). For ex ampl e:

Keeping your method calls in bounds...

Her e’s a Car c l ass t hat demonst r at es al l t he w ay s y ou c an c al l


met hods and st i l l adher e t o t he Pr i nc i pl e of Least Know l edge:

there are no Dumb Questions


Q: There is another principle called the Law of Demeter; how
are they related?

A: The t w o ar e one and t he same, and y ou’l l enc ount er t hese t er ms


b ei ng used i nt er c hangeab l y . W e pr ef er t o use t he Pr i nc i pl e of
Least Know l edge f or a c oupl e of r easons: (1 ) t he name i s mor e
i nt ui t i v e, and (2) t he use of t he w or d “Law ” i mpl i es w e al w ay s hav e
t o appl y t hi s pr i nc i pl e. In f ac t , no pr i nc i pl e i s a l aw ; al l pr i nc i pl es
shoul d b e used w hen and w her e t hey ar e hel pf ul . A l l desi gn
i nv ol v es t r adeof f s (ab st r ac t i ons v er sus speed, spac e v er sus t i me,
and so on) and w hi l e pr i nc i pl es pr ov i de gui danc e, y ou shoul d t ak e
al l f ac t or s i nt o ac c ount b ef or e appl y i ng t hem.

Q: Are there any disadv antages to apply ing the Principle of


Least Knowledge?

A: Yes; w hi l e t he pr i nc i pl e r educ es t he dependenc i es b et w een


ob jec t s and st udi es hav e show n t hi s r educ es sof t w ar e mai nt enanc e,
i t i s al so t he c ase t hat appl y i ng t hi s pr i nc i pl e r esul t s i n mor e
“w r apper ” c l asses b ei ng w r i t t en t o handl e met hod c al l s t o ot her
c omponent s. Thi s c an r esul t i n i nc r eased c ompl ex i t y and
dev el opment t i me as w el l as dec r eased r unt i me per f or manc e.
SH AR PEN YO U R PEN C IL
Do either of these classes violate the Principle of Least Knowledge? Why
or why not?

B R AIN PO W ER
Can you think of a common use of Java that violates the Principle of Least
Knowledge?

Should you care?

Answer: How about System.out.println()?

The Facade Pattern and the Principle of Least


Knowledge

Tools for your Design Toolbox


Your t ool b ox i s st ar t i ng t o get heav y ! In t hi s c hapt er w e’v e added a
c oupl e of pat t er ns t hat al l ow us t o al t er i nt er f ac es and r educ e
c oupl i ng b et w een c l i ent s and t he sy st ems t hey use.
B U L L ET PO IN T S

When you need to use an existing class and its interface is not
the one you need, use an adapter.

When you need to simplify and unify a large interface or


complex set of interfaces, use a facade.

An adapter changes an interface into one a client expects.

A facade decouples a client from a complex subsystem.

Implementing an adapter may require little work or a great deal


of work depending on the size and complexity of the target
interface.

Implementing a facade requires that we compose the facade


with its subsystem and use delegation to perform the work of the
facade.

T here are two forms of the Adapter Pattern: object and class
adapters. Class adapters require multiple inheritance.

You can implement more than one facade for a subsystem.

An adapter wraps an object to change its interface, a decorator


wraps an object to add new behaviors and responsibilities, and
a facade “wraps” a set of objects to simplify.

Design Patterns Crossword


Yes, i t ’s anot her c r ossw or d. A l l of t he sol ut i on w or ds ar e f r om t hi s
c hapt er .

ACROSS

1 . Tr ue or f al se? A dapt er s c an w r ap onl y one ob jec t .

5. A n A dapt er __________ an i nt er f ac e.

6. Mov i e w e w at c hed (f i v e w or ds).

1 0. If i n Br i t ai n, y ou mi ght need one of t hese (t w o w or ds).

1 1 . A dapt er w i t h t w o r ol es (t w o w or ds).

1 4. Fac ade st i l l ________ l ow -l ev el ac c ess.

1 5. Duc k s do i t b et t er t han Tur k ey s.

1 6. Di sadv ant age of t he Pr i nc i pl e of Least Know l edge: t oo many


__________.

1 7 . A __________ si mpl i f i es an i nt er f ac e.

1 9. N ew A mer i c an dr eam (t w o w or ds).

DOWN

2. Dec or at or c al l ed A dapt er t hi s (t hr ee w or ds).

3. One adv ant age of Fac ade.

4. Pr i nc i pl e t hat w asn’t as easy as i t sounded (t w o w or ds).

7 . A __________ adds new b ehav i or .

8. Masquer adi ng as a Duc k .

9. Ex ampl e t hat v i ol at es t he Pr i nc i pl e of Least Know l edge:


Sy st em.out .__________.

1 2. N o mov i e i s c ompl et e w i t hout t hi s.

1 3. A dapt er c l i ent uses t he __________ i nt er f ac e.

1 8. A n A dapt er and a Dec or at or c an b e sai d t o ________ an ob jec t .

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

We’re on an encapsulation roll; we’v e encapsulated obj ect


creation, method inv ocation, complex interfaces, ducks,
pizzas...what could be next? W e’r e goi ng t o get dow n t o
enc apsul at i ng pi ec es of al gor i t hms so t hat sub c l asses c an hook
t hemsel v es r i ght i nt o a c omput at i on any t i me t hey w ant . W e’r e
ev en goi ng t o l ear n ab out a desi gn pr i nc i pl e i nspi r ed b y
Hol l y w ood. Let ’s get st ar t ed...

It’s time for some more caffeine


Some peopl e c an’t l i v e w i t hout t hei r c of f ee; some peopl e c an’t l i v e
w i t hout t hei r t ea. The c ommon i ngr edi ent ? Caf f ei ne, of c our se!

But t her e’s mor e; t ea and c of f ee ar e made i n v er y si mi l ar w ay s. Let ’s


c hec k i t out :

Whipping up some coffee and tea classes (in Java)

Let ’s pl ay “c odi ng b ar i st a” and w r i t e some c ode f or c r eat i ng c of f ee


and t ea.

Her e’s t he c of f ee:


And now the Tea...

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:

Let’s abstract that Coffee and Tea


It l ook s l i k e w e’v e got a pr et t y st r ai ght f or w ar d desi gn ex er c i se on
our hands w i t h t he Cof f ee and Tea c l asses. Your f i r st c ut mi ght hav e
l ook ed somet hi ng l i k e t hi s:
B R AIN PO W ER
Did we do a good job on the redesign? Hmmmm, take another look. Are we
overlooking some other commonality? What are other ways that Coffee and
Tea are similar?

Taking the design further...


So w hat el se do Cof f ee and Tea hav e i n c ommon? Let ’s st ar t w i t h t he
r ec i pes.

N ot i c e t hat b ot h r ec i pes f ol l ow t he same al gor i t hm:

So, c an w e f i nd a w ay t o ab st r ac t pr epar eRec i pe() t oo? Yes, l et ’s f i nd


out ...

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)...

1 . The f i r st pr ob l em w e hav e i s t hat Cof f ee uses


b r ew Cof f eeGr i nds() and addSugar A ndMi l k () met hods,
w hi l e Tea uses st eepTeaBag() and addLemon() met hods.

Let ’s t hi nk t hr ough t hi s: st eepi ng and b r ew i ng ar en’t so


di f f er ent ; t hey ’r e pr et t y anal ogous. So l et ’s mak e a new
met hod name, say , b r ew (), and w e’l l use t he same name
w het her w e’r e b r ew i ng c of f ee or st eepi ng t ea.

Li k ew i se, addi ng sugar and mi l k i s pr et t y muc h t he same


as addi ng a l emon: b ot h ar e addi ng c ondi ment s t o t he
b ev er age. Let ’s al so mak e up a new met hod name,
addCondi ment s(), t o handl e t hi s. So, our new
pr epar eRec i pe() met hod w i l l l ook l i k e t hi s:

void prepareRecipe() {
boilWater();
brew();
pourInCup();
addCondiments();
}

2. N ow w e hav e a new pr epar eRec i pe() met hod, b ut w e need


t o f i t i t i nt o t he c ode. To do t hi s w e’l l st ar t w i t h t he
Caf f ei neBev er age super c l ass:

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:

What have we done?

Meet the Template Method


W e’v e b asi c al l y just i mpl ement ed t he Templ at e Met hod Pat t er n.
W hat ’s t hat ? Let ’s l ook at t he st r uc t ur e of t he Caf f ei neBev er age
c l ass; i t c ont ai ns t he ac t ual “t empl at e met hod”:

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 .

Let’s make some tea...

Let ’s st ep t hr ough mak i ng a t ea and t r ac e t hr ough how t he t empl at e


met hod w or k s. You’l l see t hat t he t empl at e met hod c ont r ol s t he
al gor i t hm; at c er t ai n poi nt s i n t he al gor i t hm, i t l et s t he sub c l ass
suppl y t he i mpl ement at i on of t he st eps...
What did the Template Method get us?

Underpowered Tea & New, hip CaffeineBeverage powered by


Coffee implementation Template Method

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.

Knowledge of the algorithm The CaffeineBeverage class concentrates knowledge


and how to implement it is about the algorithm and relies on subclasses to provide
distributed over many complete implementations.
classes.

Template Method Pattern defined


You’v e seen how t he Templ at e Met hod Pat t er n w or k s i n our Tea and
Cof f ee ex ampl e; now , c hec k out t he of f i c i al def i ni t i on and nai l
dow n al l t he det ai l s:

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.

Thi s pat t er n i s al l ab out c r eat i ng a t empl at e f or an al gor i t hm.


W hat ’s a t empl at e? A s y ou’v e seen i t ’s just a met hod; mor e
spec i f i c al l y , i t ’s a met hod t hat def i nes an al gor i t hm as a set of st eps.
One or mor e of t hese st eps i s def i ned t o b e ab st r ac t and
i mpl ement ed b y a sub c l ass. Thi s ensur es t he al gor i t hm’s st r uc t ur e
st ay s unc hanged, w hi l e sub c l asses pr ov i de some par t of t he
i mpl ement at i on.

Let ’s c hec k out t he c l ass di agr am:


C O D E U P C L O SE
Let’s take a closer look at how the AbstractClass is defined, including the
template method and primitive operations.

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:

Hooked on Template Method...


A hook i s a met hod t hat i s dec l ar ed i n t he ab st r ac t c l ass, b ut onl y
gi v en an empt y or def aul t i mpl ement at i on. Thi s gi v es sub c l asses
t he ab i l i t y t o “hook i nt o” t he al gor i t hm at v ar i ous poi nt s, i f t hey
w i sh; a sub c l ass i s al so f r ee t o i gnor e t he hook .
Ther e ar e sev er al uses of hook s; l et ’s t ak e a l ook at one now . W e’l l
t al k ab out a f ew ot her uses l at er :

Using the hook


To use t he hook , w e ov er r i de i t i n our sub c l ass. Her e, t he hook
c ont r ol s w het her t he Caf f ei neBev er age c l ass ev al uat es a c er t ai n
par t of t he al gor i t hm—t hat i s, w het her i t adds a c ondi ment t o t he
b ev er age.

How do w e k now w het her t he c ust omer w ant s t he c ondi ment ? Just
ask !

Let’s run the Test Drive


Ok ay , t he w at er ’s b oi l i ng... Her e’s t he t est c ode w her e w e c r eat e a
hot t ea and a hot c of f ee.

And let’s give it a run...


You k now w hat ? W e agr ee w i t h y ou. But y ou hav e t o admi t b ef or e
y ou t hought of t hat , i t w as a pr et t y c ool ex ampl e of how a hook c an
b e used t o c ondi t i onal l y c ont r ol t he f l ow of t he al gor i t hm i n t he
ab st r ac t c l ass. Ri ght ?

W e’r e sur e y ou c an t hi nk of many ot her mor e r eal i st i c sc enar i os


w her e y ou c oul d use t he t empl at e met hod and hook s i n y our ow n
c ode.

there are no Dumb Questions


Q: When I ’m creating a template method, how do I know when
to use abstract methods and when to use hooks?

A: U se ab st r ac t met hods w hen y our sub c l ass MU ST pr ov i de an


i mpl ement at i on of t he met hod or st ep i n t he al gor i t hm. U se hook s
w hen t hat par t of t he al gor i t hm i s opt i onal . W i t h hook s, a sub c l ass
may c hoose t o i mpl ement t hat hook , b ut i t doesn’t hav e t o.

Q: What are hooks really supposed to be used for?

A: Ther e ar e a f ew uses of hook s. A s w e just sai d, a hook may pr ov i de


a w ay f or a sub c l ass t o i mpl ement an opt i onal par t of an al gor i t hm,
or i f i t i sn’t i mpor t ant t o t he sub c l ass’s i mpl ement at i on, i t c an sk i p
i t . A not her use i s t o gi v e t he sub c l ass a c hanc e t o r eac t t o some st ep
i n t he t empl at e met hod t hat i s ab out t o happen or just happened.
For i nst anc e, a hook met hod l i k e just Reor der edLi st () al l ow s t he
sub c l ass t o per f or m some ac t i v i t y (suc h as r edi spl ay i ng an
onsc r een r epr esent at i on) af t er an i nt er nal l i st i s r eor der ed. A s
y ou’v e seen, a hook c an al so pr ov i de a sub c l ass w i t h t he ab i l i t y t o
mak e a dec i si on f or t he ab st r ac t c l ass.

Q: Does a subclass hav e to implement all the abstract methods


in the AbstractClass?

A: Yes, eac h c onc r et e sub c l ass def i nes t he ent i r e set of ab st r ac t


met hods and pr ov i des a c ompl et e i mpl ement at i on of t he undef i ned
st eps of t he t empl at e met hod’s al gor i t hm.

Q: I t seems like I should keep my abstract methods small in


number; otherwise, it will be a big j ob to implement them in the
subclass.

A: That ’s a good t hi ng t o k eep i n mi nd w hen y ou w r i t e t empl at e


met hods. Somet i mes y ou c an do t hi s b y not mak i ng t he st eps of y our
al gor i t hm t oo gr anul ar . But i t ’s ob v i ousl y a t r adeof f : t he l ess
gr anul ar i t y , t he l ess f l ex i b i l i t y .

Rememb er , t oo, t hat some st eps w i l l b e opt i onal , so y ou c an


i mpl ement t hese as hook s r at her t han ab st r ac t met hods, easi ng t he
b ur den on t he sub c l asses of y our ab st r ac t c l ass.

The Hollywood Principle


W e’v e got anot her desi gn pr i nc i pl e f or y ou; i t ’s c al l ed t he
Hol l y w ood Pr i nc i pl e:
Easy t o r ememb er , r i ght ? But w hat has i t got t o do w i t h OO desi gn?

The Hol l y w ood Pr i nc i pl e gi v es us a w ay t o pr ev ent “dependenc y


r ot .” Dependenc y r ot happens w hen y ou hav e hi gh-l ev el
c omponent s dependi ng on l ow -l ev el c omponent s dependi ng on
hi gh-l ev el c omponent s dependi ng on si dew ay s c omponent s
dependi ng on l ow -l ev el c omponent s, and so on. W hen r ot set s i n, no
one c an easi l y under st and t he w ay a sy st em i s desi gned.

W i t h t he Hol l y w ood Pr i nc i pl e, w e al l ow l ow -l ev el c omponent s t o


hook t hemsel v es i nt o a sy st em, b ut t he hi gh-l ev el c omponent s
det er mi ne w hen t hey ar e needed, and how . In ot her w or ds, t he hi gh-
l ev el c omponent s gi v e t he l ow -l ev el c omponent s t he “don’t c al l us,
w e’l l c al l y ou” t r eat ment .

The Hollywood Principle and Template Method


The c onnec t i on b et w een t he Hol l y w ood Pr i nc i pl e and t he
Templ at e Met hod Pat t er n i s pr ob ab l y somew hat appar ent : w hen w e
desi gn w i t h t he Templ at e Met hod Pat t er n, w e’r e t el l i ng sub c l asses,
“don’t c al l us, w e’l l c al l y ou.” How ? Let ’s t ak e anot her l ook at our
Caf f ei neBev er age desi gn:

B R AIN PO W ER
What other patterns make use of the Hollywood Principle?

T he Factory Method and Observer; any others?

there are no Dumb Questions


Q: How does the Holly wood Principle relate to the Dependency
I nv ersion Principle that we learned a few chapters back?

A: The Dependenc y Inv er si on Pr i nc i pl e t eac hes us t o av oi d t he use


of c onc r et e c l asses and i nst ead w or k as muc h as possi b l e w i t h
ab st r ac t i ons. The Hol l y w ood Pr i nc i pl e i s a t ec hni que f or b ui l di ng
f r amew or k s or c omponent s so t hat l ow er -l ev el c omponent s c an b e
hook ed i nt o t he c omput at i on, b ut w i t hout c r eat i ng dependenc i es
b et w een t he l ow er -l ev el c omponent s and t he hi gher -l ev el l ay er s.
So, t hey b ot h hav e t he goal of dec oupl i ng, b ut t he Dependenc y
Inv er si on Pr i nc i pl e mak es a muc h st r onger and mor e gener al
st at ement ab out how t o av oi d dependenc i es i n desi gn.

The Hol l y w ood Pr i nc i pl e gi v es us a t ec hni que f or c r eat i ng desi gns


t hat al l ow l ow -l ev el st r uc t ur es t o i nt er oper at e w hi l e pr ev ent i ng
ot her c l asses f r om b ec omi ng t oo dependent on t hem.

Q: I s a low-lev el component disallowed from calling a method in


a higher-lev el component?

A: N ot r eal l y . In f ac t , a l ow -l ev el c omponent w i l l of t en end up


c al l i ng a met hod def i ned ab ov e i t i n t he i nher i t anc e hi er ar c hy
pur el y t hr ough i nher i t anc e. But w e w ant t o av oi d c r eat i ng
ex pl i c i t c i r c ul ar dependenc i es b et w een t he l ow -l ev el c omponent
and t he hi gh-l ev el ones.

W H O D O ES W H AT ?
Match each pattern with its description:

Pattern Description

Template Encapsulate interchangeable behaviors and use delegation to


Method decide which behavior to use.

Strategy Subclasses decide how to implement steps in an algorithm.

Factory Subclasses decide which concrete classes to instantiate.


Method

Template Methods in the Wild

The Templ at e Met hod Pat t er n i s a v er y c ommon pat t er n and y ou’r e


goi ng t o f i nd l ot s of i t i n t he w i l d. You’v e got t o hav e a k een ey e,
t hough, b ec ause t her e ar e many i mpl ement at i ons of t he t empl at e
met hods t hat don’t qui t e l ook l i k e t he t ex t b ook desi gn of t he
pat t er n.

Thi s pat t er n show s up so of t en b ec ause i t ’s a gr eat desi gn t ool f or


c r eat i ng f r amew or k s, w her e t he f r amew or k c ont r ol s how
somet hi ng get s done, b ut l eav es y ou (t he per son usi ng t he
f r amew or k ) t o spec i f y y our ow n det ai l s ab out w hat i s ac t ual l y
happeni ng at eac h st ep of t he f r amew or k ’s al gor i t hm.

Let ’s t ak e a l i t t l e saf ar i t hr ough a f ew uses i n t he w i l d (w el l , ok ay ,


i n t he Jav a A PI)...

Sorting with Template Method


W hat ’s somet hi ng w e of t en need t o do w i t h ar r ay s? Sor t t hem!

Rec ogni zi ng t hat , t he desi gner s of t he Jav a A r r ay s c l ass hav e


pr ov i ded us w i t h a handy t empl at e met hod f or sor t i ng. Let ’s t ak e a
l ook at how t hi s met hod oper at es:

We’ve got some ducks to sort...


Let ’s say y ou hav e an ar r ay of duc k s t hat y ou’d l i k e t o sor t . How do
y ou do i t ? W el l , t he sor t () t empl at e met hod i n A r r ay s gi v es us t he
al gor i t hm, b ut y ou need t o t el l i t how t o c ompar e duc k s, w hi c h y ou
do b y i mpl ement i ng t he c ompar eTo() met hod... Mak e sense?

Good poi nt . Her e’s t he deal : t he desi gner s of sor t () w ant ed i t t o b e


usef ul ac r oss al l ar r ay s, so t hey had t o mak e sor t () a st at i c met hod
t hat c oul d b e used f r om any w her e. But t hat ’s ok ay , si nc e i t w or k s
al most t he same as i f i t w er e i n a super c l ass. N ow , her e i s one mor e
det ai l : b ec ause sor t () r eal l y i sn’t def i ned i n our super c l ass, t he
sor t () met hod needs t o k now t hat y ou’v e i mpl ement ed t he
c ompar eTo() met hod, or el se y ou don’t hav e t he pi ec e needed t o
c ompl et e t he sor t al gor i t hm.

To handl e t hi s, t he desi gner s made use of t he Compar ab l e i nt er f ac e.


A l l y ou hav e t o do i s i mpl ement t hi s i nt er f ac e, w hi c h has one
met hod (sur pr i se): c ompar eTo().
What is compareTo()?
The c ompar eTo() met hod c ompar es t w o ob jec t s and r et ur ns w het her
one i s l ess t han, gr eat er t han, or equal t o t he ot her . sor t () uses t hi s as
t he b asi s of i t s c ompar i son of ob jec t s i n t he ar r ay .

Comparing Ducks and Ducks


Ok ay , so y ou k now t hat i f y ou w ant t o sor t Duc k s, y ou’r e goi ng t o
hav e t o i mpl ement t hi s c ompar eTo() met hod; b y doi ng t hat , y ou’l l
gi v e t he A r r ay s c l ass w hat i t needs t o c ompl et e t he al gor i t hm and
sor t y our duc k s.

Her e’s t he duc k i mpl ement at i on:

Let’s sort some Ducks


Her e’s t he t est dr i v e f or sor t i ng Duc k s...
Let the sorting commence!

The making of the sorting duck machine

Let ’s t r ac e t hr ough how t he A r r ay s sor t () t empl at e met hod w or k s.


W e’l l c hec k out how t he t empl at e met hod c ont r ol s t he al gor i t hm,
and at c er t ai n poi nt s i n t he al gor i t hm, how i t ask s our Duc k s t o
suppl y t he i mpl ement at i on of a st ep...

there are no Dumb Questions


Q: I s this really the Template Method Pattern, or are y ou try ing
too hard?

A: The pat t er n c al l s f or i mpl ement i ng an al gor i t hm and l et t i ng


sub c l asses suppl y t he i mpl ement at i on of t he st eps—and t he A r r ay s
sor t () i s c l ear l y not doi ng t hat ! But , as w e k now , pat t er ns i n t he
w i l d ar en’t al w ay s just l i k e t he t ex t b ook pat t er ns. They hav e t o b e
modi f i ed t o f i t t he c ont ex t and i mpl ement at i on c onst r ai nt s.

The desi gner s of t he A r r ay s sor t () met hod had a f ew c onst r ai nt s. In


gener al , y ou c an’t sub c l ass a Jav a ar r ay and t hey w ant ed t he sor t t o
b e used on al l ar r ay s (and eac h ar r ay i s a di f f er ent c l ass). So t hey
def i ned a st at i c met hod and def er r ed t he c ompar i son par t of t he
al gor i t hm t o t he i t ems b ei ng sor t ed.

So, w hi l e i t ’s not a t ex t b ook t empl at e met hod, t hi s i mpl ement at i on


i s st i l l i n t he spi r i t of t he Templ at e Met hod Pat t er n. A l so, b y
el i mi nat i ng t he r equi r ement t hat y ou hav e t o sub c l ass A r r ay s t o
use t hi s al gor i t hm, t hey ’v e made sor t i ng i n some w ay s mor e
f l ex i b l e and usef ul .

Q: This implementation of sorting actually seems more like the


Strategy Pattern than the Template Method Pattern. Why do we
consider it Template Method?

A: You’r e pr ob ab l y t hi nk i ng t hat b ec ause t he St r at egy Pat t er n uses


ob jec t c omposi t i on. You’r e r i ght i n a w ay —w e’r e usi ng t he A r r ay s
ob jec t t o sor t our ar r ay , so t hat ’s si mi l ar t o St r at egy . But r ememb er ,
i n St r at egy , t he c l ass t hat y ou c ompose w i t h i mpl ement s t he ent i r e
al gor i t hm. The al gor i t hm t hat A r r ay s i mpl ement s f or sor t () i s
i nc ompl et e; i t needs a c l ass t o f i l l i n t he mi ssi ng c ompar eTo()
met hod. So, i n t hat w ay , i t ’s mor e l i k e Templ at e Met hod.
Q: Are there other examples of template methods in the Jav a
API ?

A: Yes, y ou’l l f i nd t hem i n a f ew pl ac es. For ex ampl e, jav a.i o has a


r ead() met hod i n Input St r eam t hat sub c l asses must i mpl ement and
i s used b y t he t empl at e met hod r ead(b y t e b [], i nt of f , i nt l en).

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?

Swingin’ with Frames

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!

If y ou hav en’t enc ount er ed JFr ame, i t ’s t he most b asi c Sw i ng


c ont ai ner and i nher i t s a pai nt () met hod. By def aul t , pai nt () does
not hi ng b ec ause i t ’s a hook ! By ov er r i di ng pai nt (), y ou c an i nser t
y our sel f i nt o JFr ame’s al gor i t hm f or di spl ay i ng i t s ar ea of t he
sc r een and hav e y our ow n gr aphi c out put i nc or por at ed i nt o t he
JFr ame. Her e’s an emb ar r assi ngl y si mpl e ex ampl e of usi ng a
JFr ame t o ov er r i de t he pai nt () hook met hod:

Custom Lists with AbstractList

Our f i nal st op on t he saf ar i : A b st r ac t Li st .


The l i st c ol l ec t i ons i n Jav a, l i k e A r r ay Li st and Li nk edLi st , ex t end
t he A b st r ac t Li st c l ass, w hi c h pr ov i des some of t he b asi c
i mpl ement at i ons f or l i st b ehav i or . If y ou w ant t o c r eat e y our ow n
c ust om l i st —say , a l i st t hat c ont ai ns onl y St r i ngs—y ou c an do t hat
b y ex t endi ng A b st r ac t Li st so y ou get t hat b asi c l i st b ehav i or f or
f r ee.

A b st r ac t Li st has a t empl at e met hod, sub Li st (), t hat r el i es on t w o


ab st r ac t met hods, get () and si ze(). So w hen y ou ex t end A b st r ac t Li st
t o c r eat e y our ow n c ust om l i st , y ou’l l pr ov i de i mpl ement at i ons f or
t hese met hods.

Her e’s an i mpl ement at i on of a c ust om l i st t hat c ont ai ns onl y St r i ng


ob jec t s, and uses ar r ay s f or t he under l y i ng i mpl ement at i on:

Test t he sub Li st () t empl at e met hod i n y our My St r i ngLi st


i mpl ement at i on l i k e t hi s:

Toni ght ’s t al k : Template Method and Strategy compare


methods.
Template Method: Strategy:

Hey Strategy, what are you doing in my


chapter? I figured I’d get stuck with
someone boring like Factory Method.

Nope, it’s me, although be careful—you


and Factory Method are related, aren’t
you?

I was just kidding! But seriously, what


are you doing here? We haven’t heard
from you in seven chapters!

I’d heard you were on the final draft of


your chapter and I thought I’d swing by to
see how it was going. We have a lot in
common, so I thought I might be able to
help...

You might want to remind the reader


what you’re all about, since it’s been so
long.

I don’t know, since Chapter 1, people have


been stopping me in the street saying,
“Aren’t you that pattern...?” So I think they
know who I am. But for your sake: I define
a family of algorithms and make them
interchangeable. Since each algorithm is
encapsulated, the client can use different
algorithms easily.

Hey, that does sound a lot like what I do.


But my intent’s a little different from
yours; my job is to define the outline of an
algorithm, but let my subclasses do some
of the work. That way, I can have
different implementations of an
algorithm’s individual steps, but keep
control over the algorithm’s structure.
Seems like you have to give up control of
your algorithms.

I’m not sure I’d put it quite like that...and


anyway, I’m not stuck using inheritance for
algorithm implementations. I offer clients a
choice of algorithm implementation
through object composition.

I remember that. But I have more control


over my algorithm and I don’t duplicate
code. In fact, if every part of my
algorithm is the same except for, say, one
line, then my classes are much more
efficient than yours. All my duplicated
code gets put into the superclass, so all
the subclasses can share it.

You might be a little more efficient (just a


little) and require fewer objects. And you
might also be a little less complicated in
comparison to my delegation model, but
I’m more flexible because I use object
composition. With me, clients can change
their algorithms at runtime simply by using
a different strategy object. Come on, they
didn’t choose me for Chapter 1 for nothing!

Yeah, well, I’m real happy for ya, but


don’t forget I’m the most used pattern
around. Why? Because I provide a
fundamental method for code reuse that
allows subclasses to specify behavior. I’m
sure you can see that this is perfect for
creating frameworks.

Yeah, I guess...but what about dependency?


You’re way more dependent than me.

How’s that? My superclass is abstract.

But you have to depend on methods


implemented in your subclasses, which are
part of your algorithm. I don’t depend on
anyone; I can do the entire algorithm
myself!

Like I said, Strategy, I’m real happy for


you. Thanks for stopping by, but I’ve got
to get the rest of this chapter done.

Okay, okay, don’t get touchy. I’ll let you


work, but let me know if you need my
special techniques anyway; I’m always glad
to help.

Got it. Don’t call us, we’ll call you...

Design Patterns Crossword


It ’s t hat t i me agai n...

ACROSS
1 . Huey , Loui e, and Dew ey al l w ei gh __________ pounds.

2. The t empl at e met hod i s usual l y def i ned i n an _______ c l ass.

4. In t hi s c hapt er w e gav e y ou mor e _________.

7 . The st eps i n t he al gor i t hm t hat must b e suppl i ed b y t he


sub c l asses ar e usual l y dec l ar ed ___________.

1 1 . The JFr ame hook met hod t hat w e ov er r ode t o pr i nt “I r ul e!!”

1 2. ___________ has a sub Li st () t empl at e met hod.

1 3. Ty pe of sor t used i n A r r ay s.

1 4. The Templ at e Met hod Pat t er n uses _____________ t o def er


i mpl ement at i on t o ot her c l asses.

1 5. “Don’t c al l us, w e’l l c al l y ou” i s k now n as t he _________


Pr i nc i pl e.

DOWN

1 . Cof f ee and ______.

3. Fac t or y Met hod i s a __________ of Templ at e Met hod.

5. A t empl at e met hod def i nes t he st eps of an ________.

6. Bi g-headed pat t er n.

8. _______ al gor i t hm st eps ar e i mpl ement ed b y hook met hods.

9. Our f av or i t e c of f ee shop i n Ob jec t v i l l e.

1 0. The A r r ay s c l ass i mpl ement s i t s t empl at e met hod as a ______


met hod.

1 5. A met hod i n t he ab st r ac t super c l ass t hat does not hi ng or


pr ov i des def aul t b ehav i or i s c al l ed a ____________ met hod.

Tools for your Design Toolbox


W e’v e added Templ at e Met hod t o y our t ool b ox . W i t h Templ at e
Met hod, y ou c an r euse c ode l i k e a pr o w hi l e k eepi ng c ont r ol of
y our al gor i t hms.
B U L L ET PO IN T S

A template method defines the steps of an algorithm, deferring


to subclasses for the implementation of those steps.

T he Template Method Pattern gives us an important technique


for code reuse.

T he template method’s abstract class may define concrete


methods, abstract methods, and hooks.

Abstract methods are implemented by subclasses.

Hooks are methods that do nothing or default behavior in the


abstract class, but may be overridden in the subclass.

To prevent subclasses from changing the algorithm in the


template method, declare the template method as final.

T he Hollywood Principle guides us to put decision making in


high-level modules that can decide how and when to call low-
level modules.

You’ll see lots of uses of the Template Method Pattern in real-


world code, but (as with any pattern) don’t expect it all to be
designed “by the book.”

T he Strategy and Template Method Patterns both encapsulate


algorithms, the first by composition and the other by inheritance.

Factory Method is a specialization of Template Method.

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:

Design Patterns Crossword Solution


It ’s t hat t i me agai n...
Chapter 9. Well-Managed
Collections: The Iterator and
Composite Patterns

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 .

Breaking News: Objectville Diner and Objectville


Pancake House Merge
That ’s gr eat new s! N ow w e c an get t hose del i c i ous panc ak e
b r eak f ast s at t he Panc ak e House and t hose y ummy l unc hes at t he
Di ner al l i n one pl ac e. But t her e seems t o b e a sl i ght pr ob l em...

Check out the Menu Items


A t l east Lou and Mel agr ee on t he i mpl ement at i on of t he MenuIt ems.
Let ’s c hec k out t he i t ems on eac h menu, and al so t ak e a l ook at t he
i mpl ement at i on.
Lou and Mel’s Menu implementations
N ow l et ’s t ak e a l ook at w hat Lou and Mel ar e ar gui ng ab out . They
b ot h hav e l ot s of t i me and c ode i nv est ed i n t he w ay t hey st or e t hei r
menu i t ems i n a menu, and l ot s of ot her c ode t hat depends on i t .
What’s the problem with having two different menu
representations?
To see w hy hav i ng t w o di f f er ent menu r epr esent at i ons c ompl i c at es
t hi ngs, l et ’s t r y i mpl ement i ng a c l i ent t hat uses t he t w o menus.
Imagi ne y ou hav e b een hi r ed b y t he new c ompany f or med b y t he
mer ger of t he Di ner and t he Panc ak e House t o c r eat e a Jav a-
enab l ed w ai t r ess (t hi s i s Ob jec t v i l l e, af t er al l ). The spec f or t he
Jav a-enab l ed w ai t r ess spec i f i es t hat she c an pr i nt a c ust om menu
f or c ust omer s on demand, and ev en t el l y ou i f a menu i t em i s
v eget ar i an w i t hout hav i ng t o ask t he c ook —now t hat ’s an
i nnov at i on!

Let ’s c hec k out t he spec f or t he w ai t r ess, and t hen st ep t hr ough


w hat i t mi ght t ak e t o i mpl ement her ...

The Java-Enabled Waitress Specification

Implementing the spec: our first attempt


Let ’s st ar t b y st eppi ng t hr ough how w e’d i mpl ement t he
pr i nt Menu() met hod:

1 . To pr i nt al l t he i t ems on eac h menu, y ou’l l need t o c al l


t he get MenuIt ems() met hod on t he Panc ak eHouseMenu
and t he Di ner Menu t o r et r i ev e t hei r r espec t i v e menu
i t ems. N ot e t hat eac h r et ur ns a di f f er ent t y pe:

2. N ow , t o pr i nt out t he i t ems f r om t he Panc ak eHouseMenu,


w e’l l l oop t hr ough t he i t ems on t he b r eak f ast It ems
A r r ay Li st . A nd t o pr i nt out t he Di ner i t ems, w e’l l l oop
t hr ough t he A r r ay .
3. Impl ement i ng ev er y ot her met hod i n t he W ai t r ess i s
goi ng t o b e a v ar i at i on of t hi s t heme. W e’r e al w ay s goi ng
t o need t o get b ot h menus and use t w o l oops t o i t er at e
t hr ough t hei r i t ems. If anot her r est aur ant w i t h a
di f f er ent i mpl ement at i on i s ac qui r ed, t hen w e’l l hav e
th ree l oops.

SH AR PEN YO U R PEN C IL
Based on our implementation of printMenu(), which of the following apply?

A. We are coding to the PancakeHouseMenu and DinerMenu


concrete implementations, not to an interface.

B. T he Waitress doesn’t implement the Java Waitress API and so


she isn’t adhering to a standard.

C. If we decided to switch from using DinerMenu to another type of


menu that implemented its list of menu items with a hash table, we’d have
to modify a lot of code in the Waitress.

D. T he Waitress needs to know how each menu represents its


internal collection of menu items; this violates encapsulation.

E. We have duplicate code: the printMenu() method needs two


separate loops to iterate over the two different kinds of menus. And if we
added a third menu, we’d have yet another loop.

F. T he implementation isn’t based on MXML (Menu XML) and so isn’t


as interoperable as it should be.

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.

It w oul d r eal l y b e ni c e i f w e c oul d f i nd a w ay t o al l ow t hem t o


i mpl ement t he same i nt er f ac e f or t hei r menus (t hey ’r e al r eady
c l ose, ex c ept f or t he r et ur n t y pe of t he get MenuIt ems() met hod).
That w ay w e c an mi ni mi ze t he c onc r et e r ef er enc es i n t he W ai t r ess
c ode and al so hopef ul l y get r i d of t he mul t i pl e l oops r equi r ed t o
i t er at e ov er b ot h menus.

Sound good? W el l , how ar e w e goi ng t o do t hat ?

Can we encapsulate the iteration?


If w e’v e l ear ned one t hi ng i n t hi s b ook , i t ’s t o enc apsul at e w hat
v ar i es. It ’s ob v i ous w hat i s c hangi ng her e: t he i t er at i on c aused b y
di f f er ent c ol l ec t i ons of ob jec t s b ei ng r et ur ned f r om t he menus. But
c an w e enc apsul at e t hi s? Let ’s w or k t hr ough t he i dea...

1 . To i t er at e t hr ough t he b r eak f ast i t ems, w e use t he si ze()


and get () met hods on t he A r r ay Li st :

2. A nd t o i t er at e t hr ough t he l unc h i t ems w e use t he A r r ay


l engt h f i el d and t he ar r ay sub sc r i pt not at i on on t he
MenuIt em A r r ay .

3. N ow w hat i f w e c r eat e an ob jec t , l et ’s c al l i t an It er at or ,


t hat enc apsul at es t he w ay w e i t er at e t hr ough a
c ol l ec t i on of ob jec t s? Let ’s t r y t hi s on t he A r r ay Li st :
4. Let ’s t r y t hat on t he A r r ay t oo:

Meet the Iterator Pattern


W el l , i t l ook s l i k e our pl an of enc apsul at i ng i t er at i on just mi ght
ac t ual l y w or k ; and as y ou’v e pr ob ab l y al r eady guessed, i t i s a
Desi gn Pat t er n c al l ed t he It er at or Pat t er n.

The f i r st t hi ng y ou need t o k now ab out t he It er at or Pat t er n i s t hat


i t r el i es on an i nt er f ac e c al l ed It er at or . Her e’s one possi b l e
It er at or i nt er f ac e:

N ow , onc e w e hav e t hi s i nt er f ac e, w e c an i mpl ement It er at or s f or


any k i nd of c ol l ec t i on of ob jec t s: ar r ay s, l i st s, hash maps ... pi c k
y our f av or i t e c ol l ec t i on of ob jec t s. Let ’s say w e w ant ed t o
i mpl ement t he It er at or f or t he A r r ay used i n t he Di ner Menu. It
w oul d l ook l i k e t hi s:

Let ’s go ahead and i mpl ement t hi s It er at or and i nc or por at e i t i nt o


Di ner Menu t o see how t hi s w or k s...

Adding an Iterator to DinerMenu


To add an i t er at or t o t he Di ner Menu, w e f i r st need t o def i ne t he
It er at or i nt er f ac e:
A nd now w e need t o i mpl ement a c onc r et e It er at or t hat w or k s f or
t he Di ner menu:

Reworking the DinerMenu with Iterator


Ok ay , w e’v e got t he i t er at or . Ti me t o w or k i t i nt o t he Di ner Menu;
al l w e need t o do i s add one met hod t o c r eat e a Di ner MenuIt er at or
and r et ur n i t t o t he c l i ent :

EXER C ISE
Go ahead and implement the PancakeHouseIterator yourself and make the
changes needed to incorporate it into the PancakeHouseMenu.

Fixing up the Waitress code


N ow w e need t o i nt egr at e t he i t er at or c ode i nt o t he W ai t r ess c l ass.
W e shoul d b e ab l e t o get r i d of some of t he r edundanc y i n t he
pr oc ess. Int egr at i on i s pr et t y st r ai ght f or w ar d: f i r st w e c r eat e a
pr i nt Menu() met hod t hat t ak es an It er at or ; t hen w e use t he
c r eat eIt er at or () met hod on eac h menu t o r et r i ev e t he It er at or and
pass i t t o t he new met hod.
Testing our code
It ’s t i me t o put ev er y t hi ng t o a t est . Let ’s w r i t e some t est dr i v e c ode
and see how t he W ai t r ess w or k s...

Here’s the test run...

What have we done so far?


For st ar t er s, w e’v e made our Ob jec t v i l l e c ook s v er y happy . They
set t l ed t hei r di f f er enc es and k ept t hei r ow n i mpl ement at i ons.
Onc e w e gav e t hem a Panc ak eHouseMenuIt er at or and a
Di ner MenuIt er at or , al l t hey had t o do w as add a c r eat eIt er at or ()
met hod and t hey w er e f i ni shed.

W e’v e al so hel ped our sel v es i n t he pr oc ess. The W ai t r ess w i l l b e


muc h easi er t o mai nt ai n and ex t end dow n t he r oad. Let ’s go t hr ough
ex ac t l y w hat w e di d and t hi nk ab out t he c onsequenc es:

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 The Waitress now uses an interface (Iterator).


concrete classes (MenuItem[]
and ArrayList).

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.

Making some improvements...


Ok ay , w e k now t he i nt er f ac es of Panc ak eHouseMenu and
Di ner Menu ar e ex ac t l y t he same and y et w e hav en’t def i ned a
c ommon i nt er f ac e f or t hem. So, w e’r e goi ng t o do t hat and c l ean up
t he W ai t r ess a l i t t l e mor e.

You may b e w onder i ng w hy w e’r e not usi ng t he Jav a It er at or


i nt er f ac e—w e di d t hat so y ou c oul d see how t o b ui l d an i t er at or
f r om sc r at c h. N ow t hat w e’v e done t hat , w e’r e goi ng t o sw i t c h t o
usi ng t he Jav a It er at or i nt er f ac e, b ec ause w e’l l get a l ot of l ev er age
b y i mpl ement i ng t hat i nst ead of our home-gr ow n It er at or
i nt er f ac e. W hat k i nd of l ev er age? You’l l soon see.

Fi r st , l et ’s c hec k out t he jav a.ut i l .It er at or i nt er f ac e:

Thi s i s goi ng t o b e a pi ec e of c ak e: w e just need t o c hange t he


i nt er f ac e t hat b ot h Panc ak eHouseMenuIt er at or and
Di ner MenuIt er at or ex t end, r i ght ? A l most ...ac t ual l y , i t ’s ev en easi er
t han t hat . N ot onl y does jav a.ut i l hav e i t s ow n It er at or i nt er f ac e,
b ut A r r ay Li st has an i t er at or () met hod t hat r et ur ns an i t er at or . In
ot her w or ds, w e nev er needed t o i mpl ement our ow n i t er at or f or
A r r ay Li st . How ev er , w e’l l st i l l need our i mpl ement at i on f or t he
Di ner Menu b ec ause i t r el i es on an A r r ay , w hi c h doesn’t suppor t
t he i t er at or () met hod.

there are no Dumb Questions


Q: What if I don’t want to prov ide the ability to remov e
something from the underly ing collection of obj ects?

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?

A: The b ehav i or of t he r emov e() met hod i s unspec i f i ed i f t he


c ol l ec t i on c hanges w hi l e y ou ar e i t er at i ng ov er i t . So y ou shoul d b e
c ar ef ul i n desi gni ng y our ow n mul t i t hr eaded c ode w hen ac c essi ng
a c ol l ec t i on c onc ur r ent l y .

Cleaning things up with java.util.Iterator


Let ’s st ar t w i t h t he Panc ak eHouseMenu. Changi ng i t ov er t o
jav a.ut i l .It er at or i s goi ng t o b e easy . W e just del et e t he
Panc ak eHouseMenuIt er at or c l ass, add an i mpor t jav a.ut i l .It er at or
t o t he t op of Panc ak eHouseMenu, and c hange one l i ne of t he
Panc ak eHouseMenu:

A nd t hat ’s i t , Panc ak eHouseMenu i s done.

N ow w e need t o mak e t he c hanges t o al l ow Di ner Menu t o w or k w i t h


jav a.ut i l .It er at or .
We are almost there...
N ow w e just need t o gi v e t he Menus a c ommon i nt er f ac e and r ew or k
t he W ai t r ess a l i t t l e. The Menu i nt er f ac e i s qui t e si mpl e: w e mi ght
w ant t o add a f ew mor e met hods t o i t ev ent ual l y , l i k e addIt em(), b ut
f or now w e’l l l et t he c hef s c ont r ol t hei r menus b y k eepi ng t hat
met hod out of t he pub l i c i nt er f ac e:

N ow w e need t o add an i mpl ement s Menu t o b ot h t he


Panc ak eHouseMenu and t he Di ner Menu c l ass def i ni t i ons and
updat e t he W ai t r ess c l ass:

What does this get us?


The Panc ak eHouseMenu and Di ner Menu c l asses i mpl ement an
i nt er f ac e, Menu. Thi s al l ow s t he W ai t r ess t o r ef er t o eac h menu
ob jec t usi ng t he i nt er f ac e r at her t han t he c onc r et e c l ass. So, w e’r e
r educ i ng t he dependenc y b et w een t he W ai t r ess and t he c onc r et e
c l asses b y “pr ogr ammi ng t o an i nt er f ac e, not an i mpl ement at i on.”

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.

Iterator Pattern defined


You’v e al r eady seen how t o i mpl ement t he It er at or Pat t er n w i t h
y our v er y ow n i t er at or . You’v e al so seen how Jav a suppor t s
i t er at or s i n some of i t s c ol l ec t i on-or i ent ed c l asses (A r r ay Li st ). N ow
i t ’s t i me t o c hec k out t he of f i c i al def i ni t i on of t he pat t er n:
N O TE
The Iterator Pattern provides a way to access the elements
of an aggregate object sequentially without exposing its
underlying representation.

Thi s mak es a l ot of sense: t he pat t er n gi v es y ou a w ay t o st ep


t hr ough t he el ement s of an aggr egat e w i t hout hav i ng t o k now how
t hi ngs ar e r epr esent ed under t he c ov er s. You’v e seen t hat w i t h t he
t w o i mpl ement at i ons of Menus. But t he ef f ec t of usi ng i t er at or s i n
y our desi gn i s just as i mpor t ant : onc e y ou hav e a uni f or m w ay of
ac c essi ng t he el ement s of al l y our aggr egat e ob jec t s, y ou c an w r i t e
pol y mor phi c c ode t hat w or k s w i t h any of t hese aggr egat es—just
l i k e t he pr i nt Menu() met hod, w hi c h doesn’t c ar e i f t he menu i t ems
ar e hel d i n an A r r ay or A r r ay Li st (or any t hi ng el se t hat c an c r eat e
an It er at or ), as l ong as i t c an get hol d of an It er at or .

The ot her i mpor t ant i mpac t on y our desi gn i s t hat t he It er at or


Pat t er n t ak es t he r esponsi b i l i t y of t r av er si ng el ement s and gi v es
t hat r esponsi b i l i t y t o t he i t er at or ob jec t , not t he aggr egat e ob jec t .
Thi s not onl y k eeps t he aggr egat e i nt er f ac e and i mpl ement at i on
si mpl er , i t r emov es t he r esponsi b i l i t y f or i t er at i on f r om t he
aggr egat e and k eeps t he aggr egat e f oc used on t he t hi ngs i t shoul d b e
f oc used on (managi ng a c ol l ec t i on of ob jec t s), not on i t er at i on.

Th e Ite ra to r Pa tte rn a llo w s tra v e rs a l o f th e e le m e nts


o f a n a g g re g a te w ith o ut e xp o s ing th e und e rly ing
im p le m e nta tio n.

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 .

The Iterator Pattern Structure


Let ’s c hec k out t he c l ass di agr am t o put al l t he pi ec es i n c ont ex t ...

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.

The Single Responsibility Principle


W hat i f w e al l ow ed our aggr egat es t o i mpl ement t hei r i nt er nal
c ol l ec t i ons and r el at ed oper at i ons A N D t he i t er at i on met hods?
W el l , w e al r eady k now t hat w oul d ex pand t he numb er of met hods
i n t he aggr egat e, b ut so w hat ? W hy i s t hat so b ad?

W el l , t o see w hy , y ou f i r st need t o r ec ogni ze t hat w hen w e al l ow a


c l ass t o not onl y t ak e c ar e of i t s ow n b usi ness (managi ng some k i nd
of aggr egat e) b ut al so t ak e on mor e r esponsi b i l i t i es (l i k e i t er at i on)
t hen w e’v e gi v en t he c l ass t w o r easons t o c hange. Tw o? Yup, t w o: i t
c an c hange i f t he c ol l ec t i on c hanges i n some w ay , and i t c an c hange
i f t he w ay w e i t er at e c hanges. So onc e agai n our f r i end CHA N GE i s
at t he c ent er of anot her desi gn pr i nc i pl e:

W e k now w e w ant t o av oi d c hange i n our c l asses b ec ause modi f y i ng


c ode pr ov i des al l sor t s of oppor t uni t i es f or pr ob l ems t o c r eep i n.
Hav i ng t w o w ay s t o c hange i nc r eases t he pr ob ab i l i t y t he c l ass w i l l
c hange i n t he f ut ur e, and w hen i t does, i t ’s goi ng t o af f ec t t w o
aspec t s of y our desi gn.

The sol ut i on? The pr i nc i pl e gui des us t o assi gn eac h r esponsi b i l i t y


t o one c l ass, and onl y one c l ass.

That ’s r i ght , i t ’s as easy as t hat , and t hen agai n i t ’s not : separ at i ng


r esponsi b i l i t y i n desi gn i s one of t he most di f f i c ul t t hi ngs t o do.
Our b r ai ns ar e just t oo good at seei ng a set of b ehav i or s and
gr oupi ng t hem t oget her ev en w hen t her e ar e ac t ual l y t w o or mor e
r esponsi b i l i t i es. The onl y w ay t o suc c eed i s t o b e di l i gent i n
ex ami ni ng y our desi gns and t o w at c h out f or si gnal s t hat a c l ass i s
c hangi ng i n mor e t han one w ay as y our sy st em gr ow s.

Ev e ry re s p o ns ib ility o f a cla s s is a n a re a o f p o te ntia l


ch a ng e . Mo re th a n o ne re s p o ns ib ility m e a ns m o re
th a n o ne a re a o f ch a ng e .

Th is p rincip le g uid e s us to k e e p e a ch cla s s to a s ing le


re s p o ns ib ility .

Cohesion is a term you’ll hear used as a measure of how closely a class


or a module supports a single purpose or responsibility.

We say that a module or class has high cohesion when it is designed


around a set of related functions, and we say it has low cohesion when it
is designed around a set of unrelated functions.

Cohesion is a more general concept than the Single Responsibility


Principle, but the two are closely related. Classes that adhere to the
principle tend to have high cohesion and are more maintainable than
classes that take on multiple responsibilities and have low cohesion.

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.

there are no Dumb Questions


Q: I ’v e seen other books show the I terator class diagram with
the methods first(), next(), isDone(), and currentI tem(). Why
are these methods different?

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 .

Q: I ’v e heard about “internal” iterators and “external” iterators.


What are they ? Which kind did we implement in the example?

A: W e i mpl ement ed an ex t er nal i t er at or , w hi c h means t hat t he


c l i ent c ont r ol s t he i t er at i on b y c al l i ng nex t () t o get t he nex t
el ement . A n i nt er nal i t er at or i s c ont r ol l ed b y t he i t er at or i t sel f . In
t hat c ase, b ec ause i t ’s t he i t er at or t hat ’s st eppi ng t hr ough t he
el ement s, y ou hav e t o t el l t he i t er at or w hat t o do w i t h t hose
el ement s as i t goes t hr ough t hem. That means y ou need a w ay t o pass
an oper at i on t o an i t er at or . Int er nal i t er at or s ar e l ess f l ex i b l e
t han ex t er nal i t er at or s b ec ause t he c l i ent doesn’t hav e c ont r ol of
t he i t er at i on. How ev er , some mi ght ar gue t hat t hey ar e easi er t o
use b ec ause y ou just hand t hem an oper at i on and t el l t hem t o
i t er at e, and t hey do al l t he w or k f or y ou.

Q: Could I implement an I terator that can go backward as well


as forward?

A: Def i ni t el y . In t hat c ase, y ou’d pr ob ab l y w ant t o add t w o met hods,


one t o get t o t he pr ev i ous el ement , and one t o t el l y ou w hen y ou’r e
at t he b egi nni ng of t he c ol l ec t i on of el ement s. Jav a’s Col l ec t i on
Fr amew or k pr ov i des anot her t y pe of i t er at or i nt er f ac e c al l ed
Li st It er at or . Thi s i t er at or adds pr ev i ous() and a f ew ot her met hods
t o t he st andar d It er at or i nt er f ac e. It i s suppor t ed b y any Col l ec t i on
t hat i mpl ement s t he Li st i nt er f ac e.

Q: Who defines the ordering of the iteration in a collection like


Hashtable, which is inherently unordered?

A: It er at or s i mpl y no or der i ng. The under l y i ng c ol l ec t i ons may b e


unor der ed as i n a hash t ab l e or i n a b ag; t hey may ev en c ont ai n
dupl i c at es. So or der i ng i s r el at ed t o b ot h t he pr oper t i es of t he
under l y i ng c ol l ec t i on and t o t he i mpl ement at i on. In gener al , y ou
shoul d mak e no assumpt i ons ab out or der i ng unl ess t he Col l ec t i on
doc ument at i on i ndi c at es ot her w i se.

Q: Y ou said we can write “poly morphic code” using an iterator;


can y ou explain that more?

A: W hen w e w r i t e met hods t hat t ak e It er at or s as par amet er s, w e


ar e usi ng pol y mor phi c i t er at i on. That means w e ar e c r eat i ng c ode
t hat c an i t er at e ov er any c ol l ec t i on as l ong as i t suppor t s It er at or .
W e don’t c ar e ab out how t he c ol l ec t i on i s i mpl ement ed, w e c an st i l l
w r i t e c ode t o i t er at e ov er i t .

Q: I f I ’m using Jav a, won’t I alway s want to use the


j av a.util.I terator interface so I can use my own iterator
implementations with classes that are already using the Jav a
iterators?

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.

Q: I ’v e seen an Enumeration interface in Jav a; does that


implement the I terator Pattern?

A: W e t al k ed ab out t hi s i n t he A dapt er Pat t er n c hapt er (Chapt er 7 ).


Rememb er ? The jav a.ut i l .Enumer at i on i s an ol der i mpl ement at i on
of It er at or t hat has si nc e b een r epl ac ed b y jav a.ut i l .It er at or .
Enumer at i on has t w o met hods, hasMor eEl ement s(), c or r espondi ng
t o hasN ex t (), and nex t El ement (), c or r espondi ng t o nex t (). How ev er ,
y ou’l l pr ob ab l y w ant t o use It er at or ov er Enumer at i on as mor e
Jav a c l asses suppor t i t . If y ou need t o c onv er t f r om one t o anot her ,
r ev i ew Chapt er 7 agai n w her e y ou i mpl ement ed t he adapt er f or
Enumer at i on and It er at or .

Q: I s using Jav a’s enhanced for loop related to iterators?

A: Good quest i on! It i s, and t o t ac k l e t hat quest i on w e need t o


under st and anot her i nt er f ac e—t hat i s, Jav a’s It er ab l e i nt er f ac e.
Thi s i s a good t i me t o do just t hat ...

Meet Java’s Iterable interface


You’r e al r eady up t o speed on Jav a’s I terator i nt er f ac e, b ut t her e’s
anot her i nt er f ac e y ou need t o meet : I terable. The It er ab l e
i nt er f ac e i s i mpl ement ed b y ev er y Col l ec t i on t y pe i n Jav a. Guess
w hat ? In y our c ode usi ng t he A r r ay Li st , y ou’v e al r eady b een usi ng
t hi s i nt er f ac e. Let ’s t ak e a l ook at t he It er ab l e i nt er f ac e:

If a c l ass i mpl ement s It er ab l e, w e k now t hat t he c l ass i mpl ement s


an i t er at or () met hod. That met hod r et ur ns an i t er at or t hat
i mpl ement s t he It er at or i nt er f ac e. Thi s i nt er f ac e al so i nc l udes a
def aul t f or Eac h() met hod t hat c an b e used as anot her w ay t o i t er at e
t hr ough t he c ol l ec t i on. In addi t i on t o al l t hat , Jav a ev en pr ov i des
some ni c e sy nt ac t i c sugar f or i t er at i on, w i t h i t s enhanc ed f or l oop.
Let ’s see how t hat w or k s.
N O TE
The Iterable interface also includes the spliterator() method,
which provides even more advanced ways to iterate through a
collection.

Java’s enhanced for loop


Let ’s t ak e an ob jec t w hose c l ass i mpl ement s t he It er ab l e
i nt er f ac e...w hy not t he A r r ay Li st c ol l ec t i on w e used f or t he
Panc ak e House menu i t ems:

List<MenuItem> menuItems = new ArrayList<MenuItem>();

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:

Or , gi v en w e k now A r r ay Li st i s an It er ab l e, w e c oul d use Jav a’s


enhanc ed f or shor t hand:

Not so fast; Arrays are not Iterables


W e hav e some b ad new s: t he Di ner may not hav e made t he b est
dec i si on usi ng an A r r ay as t he b asi s f or i t s menus. A s i t t ur ns out ,
A r r ay s ar e not Jav a Col l ec t i ons and so t hey don’t i mpl ement t he
It er ab l e i nt er f ac e. Gi v en t hat , w e c an’t as easi l y c onsol i dat e our
W ai t r ess c ode i nt o one met hod t hat t ak es an It er ab l e and use i t
w i t h b ot h t he Panc ak e House’s b r eak f ast It ems and t he Di ner ’s
l unc hIt ems. If y ou t r y t o c hange t he W ai t r ess’s pr i nt Menu() met hod
t o t ak e an It er ab l e i nst ead of an It er at or , and use t he f or -eac h l oop
i nst ead of t he It er at or A PI, l i k e t hi s:

y ou’l l get a c ompi l er er r or w hen y ou t r y t o pass t he l unc hIt ems


ar r ay t o pr i nt Menu():
b ec ause, agai n, A r r ay s don’t i mpl ement t he It er ab l e i nt er f ac e.

If y ou k eep b ot h l oops i n t he W ai t r ess c ode, w e’r e b ac k t o squar e


one: t he W ai t r ess i s onc e agai n dependent on t he aggr egat e t y pes
w e’r e usi ng t o st or e t he menus, and she has dupl i c at e c ode: one l oop
f or t he A r r ay Li st , and one l oop f or t he A r r ay .

So w hat do w e do? W el l , t her e ar e many w ay s t o sol v e t hi s i ssue, b ut


t hey ar e a b i t of a si deshow , as w oul d b e r ef ac t or i ng our c ode. A f t er
al l , t hi s c hapt er i s ab out t he It er at or Pat t er n, not Jav a’s It er ab l e
i nt er f ac e. But t he good new s i s y ou k now ab out It er ab l e, y ou k now
i t s r el at i onshi p t o Jav a’s It er at or i nt er f ac e and t o t he It er at or
Pat t er n. So, l et ’s k eep mov i ng, as w e’v e got a gr eat i mpl ement at i on
ev en i f w e ar en’t t ak i ng adv ant age of a l i t t l e sy nt ac t i c sugar f r om
Jav a’s f or l oop.

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:

Taking a look at the Café Menu


Her e’s t he c af é menu. It doesn’t l ook l i k e t oo muc h t r oub l e t o
i nt egr at e t he Caf eMenu c l ass i nt o our f r amew or k ...l et ’s c hec k i t
out .
SH AR PEN YO U R PEN C IL
Before looking at the next page, quickly jot down the three things we have
to do to this code to fit it into our framework:

1.
____________________________________________________________
____

2.
____________________________________________________________
____

3.
____________________________________________________________
____

Reworking the Café Menu code


Let ’s r ew or k t he Caf eMenu c ode. W e’r e goi ng t o t ak e c ar e of
i mpl ement i ng t he Menu i nt er f ac e, and w e al so need t o deal w i t h
c r eat i ng an It er at or f or t he v al ues st or ed i n t he HashMap. Thi ngs
ar e a l i t t l e di f f er ent t han w hen w e di d t he same f or t he A r r ay Li st ;
c hec k i t out ...

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?

Adding the Cafe Menu to the Waitress


N ow i t ’s t i me t o modi f y t he W ai t r ess t o suppor t our new Menu. N ow
t hat t he W ai t r ess ex pec t s It er at or s, i t shoul d b e st r ai ght f or w ar d:

Breakfast, lunch, AND dinner


Let ’s updat e our t est dr i v e t o mak e sur e t hi s al l w or k s.
Here’s the test run; check out the new dinner menu from the
Café!

What did we do?

We decoupled the Waitress....

...and we made the Waitress more extensible

But there’s more!

Iterators and Collections


W e’v e b een usi ng a c oupl e of c l asses t hat ar e par t of t he Jav a
Col l ec t i ons Fr amew or k . Thi s “f r amew or k ” i s just a set of c l asses and
i nt er f ac es, i nc l udi ng A r r ay Li st , w hi c h w e’v e b een usi ng, and many
ot her s l i k e V ec t or , Li nk edLi st , St ac k , and Pr i or i t y Queue. Eac h of
t hese c l asses i mpl ement s t he jav a.ut i l .Col l ec t i on i nt er f ac e, w hi c h
c ont ai ns a b unc h of usef ul met hods f or mani pul at i ng gr oups of
ob jec t s.

Let ’s t ak e a qui c k l ook at t he i nt er f ac e:

W AT C H IT !
HashMap is one of a few classes that indirectly supports Iterator.

As you saw w hen w e implemented the CafeMenu, you could get an


Iterator from it, but only by first retrieving its Collection called values. If
you think about it, this makes sense: the HashMap holds tw o sets of
objects: keys and values. If w e w ant to iterate over its values, w e first
need to retrieve them from the HashMap, and then obtain the 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 .

Let ’s b e r eal —ev er y t i me w e add a new menu w e’r e goi ng t o hav e t o


open up t he W ai t r ess i mpl ement at i on and add mor e c ode. Can y ou
say “v i ol at i ng t he Open Cl osed Pr i nc i pl e”?

It ’s not t he W ai t r ess’s f aul t . W e’v e done a gr eat job of dec oupl i ng


t he menu i mpl ement at i on and ex t r ac t i ng t he i t er at i on i nt o an
i t er at or . But w e st i l l ar e handl i ng t he menus w i t h separ at e,
i ndependent ob jec t s—w e need a w ay t o manage t hem t oget her .

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 :

Thi s l ook s pr et t y good, al t hough w e’v e l ost t he names of t he menus,


b ut w e c oul d add t he names t o eac h menu.

Just when we thought it was safe...


N ow t hey w ant t o add a desser t sub menu.

Ok ay , now w hat ? N ow w e hav e t o suppor t not onl y mul t i pl e menus,


b ut menus w i t hi n menus.

It w oul d b e ni c e i f w e c oul d just mak e t he desser t menu an el ement


of t he Di ner Menu c ol l ec t i on, b ut t hat w on’t w or k as i t i s now
i mpl ement ed.

W hat w e w ant (somet hi ng l i k e t hi s):

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.

The r eal i t y i s t hat w e’v e r eac hed a l ev el of c ompl ex i t y suc h t hat i f


w e don’t r ew or k t he desi gn now , w e’r e nev er goi ng t o hav e a desi gn
t hat c an ac c ommodat e f ur t her ac qui si t i ons or sub menus.

So, w hat i s i t w e r eal l y need out of our new desi gn?

W e need some k i nd of a t r ee-shaped st r uc t ur e t hat w i l l


ac c ommodat e menus, sub menus, and menu i t ems.

W e need t o mak e sur e w e mai nt ai n a w ay t o t r av er se t he


i t ems i n eac h menu t hat i s at l east as c onv eni ent as w hat
w e’r e doi ng now w i t h i t er at or s.

W e may need t o t r av er se t he i t ems i n a mor e f l ex i b l e


manner . For i nst anc e, w e mi ght need t o i t er at e ov er onl y
t he Di ner ’s desser t menu, or w e mi ght need t o i t er at e ov er
t he Di ner ’s ent i r e menu, i nc l udi ng t he desser t sub menu.

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.

The Composite Pattern defined


That ’s r i ght ; w e’r e goi ng t o i nt r oduc e anot her pat t er n t o sol v e t hi s
pr ob l em. W e di dn’t gi v e up on It er at or —i t w i l l st i l l b e par t of our
sol ut i on—how ev er , t he pr ob l em of managi ng menus has t ak en on a
new di mensi on t hat It er at or doesn’t sol v e. So, w e’r e goi ng t o st ep
b ac k and sol v e i t w i t h t he Composi t e Pat t er n.

W e’r e not goi ng t o b eat ar ound t he b ush on t hi s pat t er n; w e’r e goi ng


t o go ahead and r ol l out t he of f i c i al def i ni t i on now :
N O TE
The Composite Pattern allows you to compose objects into
tree structures to represent part-whole hierarchies. Composite
lets clients treat individual objects and compositions of objects
uniformly.

Let ’s t hi nk ab out t hi s i n t er ms of our menus: t hi s pat t er n gi v es us a


w ay t o c r eat e a t r ee st r uc t ur e t hat c an handl e a nest ed gr oup of
menus and menu i t ems i n t he same st r uc t ur e. By put t i ng menus and
i t ems i n t he same st r uc t ur e w e c r eat e a par t -w hol e hi er ar c hy —
t hat i s, a t r ee of ob jec t s t hat i s made of par t s (menus and menu
i t ems) b ut t hat c an b e t r eat ed as a w hol e, l i k e one b i g üb er menu.

Onc e w e hav e our üb er menu, w e c an use t hi s pat t er n t o t r eat


“i ndi v i dual ob jec t s and c omposi t i ons uni f or ml y .” W hat does t hat
mean? It means i f w e hav e a t r ee st r uc t ur e of menus, sub menus, and
per haps sub sub menus al ong w i t h menu i t ems, t hen any menu i s a
“c omposi t i on” b ec ause i t c an c ont ai n b ot h ot her menus and menu
i t ems. The i ndi v i dual ob jec t s ar e just t he menu i t ems—t hey don’t
hol d ot her ob jec t s. A s y ou’l l see, usi ng a desi gn t hat f ol l ow s t he
Composi t e Pat t er n i s goi ng t o al l ow us t o w r i t e some si mpl e c ode
t hat c an appl y t he same oper at i on (l i k e pr i nt i ng!) ov er t he ent i r e
menu st r uc t ur e.

Th e Co m p o s ite Pa tte rn a llo w s us to b uild s tructure s


o f o b je cts in th e fo rm o f tre e s th a t co nta in b o th
co m p o s itio ns o f o b je cts a nd ind iv id ua l o b je cts a s
no d e s .

Us ing a co m p o s ite s tructure , w e ca n a p p ly th e s a m e


o p e ra tio ns o v e r b o th co m p o s ite s a nd ind iv id ua l
o b je cts . In o th e r w o rd s , in m o s t ca s e s w e ca n ig no re
th e d iffe re nce s b e tw e e n co m p o s itio ns o f o b je cts a nd
ind iv id ua l o b je cts .
there are no Dumb Questions
Q: Component, Composite, Trees? I ’m confused.

A: A c omposi t e c ont ai ns c omponent s. Component s c ome i n t w o


f l av or s: c omposi t es and l eaf el ement s. Sound r ec ur si v e? It i s. A
c omposi t e hol ds a set of c hi l dr en; t hose c hi l dr en may b e ot her
c omposi t es or l eaf el ement s.

W hen y ou or gani ze dat a i n t hi s w ay y ou end up w i t h a t r ee


st r uc t ur e (ac t ual l y an upsi de-dow n t r ee st r uc t ur e) w i t h a
c omposi t e at t he r oot and b r anc hes of c omposi t es gr ow i ng up t o
l eav es.

Q: How does this relate to iterators?

A: Rememb er , w e’r e t ak i ng a new appr oac h. W e’r e goi ng t o r e-


i mpl ement t he menus w i t h a new sol ut i on: t he Composi t e Pat t er n.
So don’t l ook f or some magi c al t r ansf or mat i on f r om an i t er at or t o a
c omposi t e. That sai d, t he t w o w or k v er y ni c el y t oget her . You’l l soon
see t hat w e c an use i t er at or s i n a c oupl e of w ay s i n t he c omposi t e
i mpl ement at i on.

Designing Menus with Composite


So, how do w e appl y t he Composi t e Pat t er n t o our menus? To st ar t
w i t h, w e need t o c r eat e a c omponent i nt er f ac e; t hi s ac t s as t he
c ommon i nt er f ac e f or b ot h menus and menu i t ems and al l ow s us t o
t r eat t hem uni f or ml y . In ot her w or ds, w e c an c al l t he s am e met hod
on menus or menu i t ems.

N ow , i t may not mak e s ens e t o c al l some of t he met hods on a menu


i t em or a menu, b ut w e c an deal w i t h t hat , and w e w i l l i n just a
moment . But f or now , l et ’s t ak e a l ook at a sk et c h of how t he menus
ar e goi ng t o f i t i nt o a Composi t e Pat t er n st r uc t ur e:
Implementing MenuComponent
Ok ay , w e’r e goi ng t o st ar t w i t h t he MenuComponent ab st r ac t c l ass;
r ememb er , t he r ol e of t he menu c omponent i s t o pr ov i de an
i nt er f ac e f or t he l eav es and t he c omposi t e nodes. N ow y ou mi ght b e
ask i ng, “Isn’t MenuComponent pl ay i ng t w o r ol es?” It mi ght w el l b e
and w e’l l c ome b ac k t o t hat poi nt . How ev er , f or now w e’r e goi ng t o
pr ov i de a def aul t i mpl ement at i on of t he met hods so t hat i f t he
MenuIt em (t he l eaf ) or t he Menu (t he c omposi t e) doesn’t w ant t o
i mpl ement some of t he met hods (l i k e get Chi l d() f or a l eaf node), i t
c an f al l b ac k on some b asi c b ehav i or :

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.

Implementing the MenuItem


Ok ay , l et ’s gi v e t he MenuIt em c l ass a shot . Rememb er , t hi s i s t he
l eaf c l ass i n t he Composi t e di agr am, and i t i mpl ement s t he
b ehav i or of t he el ement s of t he c omposi t e.
Implementing the Composite Menu
N ow t hat w e hav e t he MenuIt em, w e just need t he c omposi t e c l ass,
w hi c h w e’r e c al l i ng Menu. Rememb er , t he c omposi t e c l ass c an hol d
MenuIt ems or ot her Menus. Ther e’s a c oupl e of met hods f r om
MenuComponent t hi s c l ass doesn’t i mpl ement , get Pr i c e() and
i sV eget ar i an(), b ec ause t hose don’t mak e a l ot of sense f or a Menu.

Good catch. Bec ause Menu i s a c omposi t e and c ont ai ns b ot h


MenuIt ems and ot her Menus, i t s pr i nt () met hod shoul d pr i nt
ev er y t hi ng i t c ont ai ns. If i t doesn’t , w e’l l hav e t o i t er at e t hr ough
t he ent i r e c omposi t e and pr i nt eac h i t em our sel v es. That k i nd of
def eat s t he pur pose of hav i ng a c omposi t e st r uc t ur e.

A s y ou’r e goi ng t o see, i mpl ement i ng pr i nt () c or r ec t l y i s easy


b ec ause w e c an r el y on eac h c omponent t o b e ab l e t o pr i nt i t sel f .
It ’s al l w onder f ul l y r ec ur si v e and gr oov y . Chec k i t out :

Fixing the print() method

Getting ready for a test drive...


It ’s ab out t i me w e t ook t hi s c ode f or a t est dr i v e, b ut w e need t o
updat e t he W ai t r ess c ode b ef or e w e do—af t er al l , she’s t he mai n
c l i ent of t hi s c ode:
Ok ay , one l ast t hi ng b ef or e w e w r i t e our t est dr i v e. Let ’s get an i dea
of w hat t he menu c omposi t e i s goi ng t o l ook l i k e at r unt i me:

Now for the test drive...


Ok ay , now w e just need a t est dr i v e. U nl i k e our pr ev i ous v er si on,
w e’r e goi ng t o handl e al l t he menu c r eat i on i n t he t est dr i v e. W e
c oul d ask eac h c hef t o gi v e us hi s new menu, b ut l et ’s get i t al l
t est ed f i r st . Her e’s t he c ode:

Getting ready for a test drive...

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 .

N ow , gi v en w e hav e b ot h t y pes of oper at i ons i n t he Component


c l ass, w e l ose a b i t of s afety b ec ause a c l i ent mi ght t r y t o do
somet hi ng i nappr opr i at e or meani ngl ess on an el ement (l i k e t r y t o
add a menu t o a menu i t em). Thi s i s a desi gn dec i si on; w e c oul d t ak e
t he desi gn i n t he ot her di r ec t i on and separ at e out t he
r esponsi b i l i t i es i nt o i nt er f ac es. Thi s w oul d mak e our desi gn saf e,
i n t he sense t hat any i nappr opr i at e c al l s on el ement s w oul d b e
c aught at c ompi l e t i me or r unt i me, b ut w e’d l ose t r anspar enc y and
our c ode w oul d hav e t o use c ondi t i onal s and t he i nst anc eof
oper at or .

So, t o r et ur n t o y our quest i on, t hi s i s a c l assi c c ase of t r adeof f . W e


ar e gui ded b y desi gn pr i nc i pl es, b ut w e al w ay s need t o ob ser v e t he
ef f ec t t hey hav e on our desi gns. Somet i mes w e pur posel y do t hi ngs
i n a w ay t hat seems t o v i ol at e t he pr i nc i pl e. In some c ases,
how ev er , t hi s i s a mat t er of per spec t i v e; f or i nst anc e, i t mi ght seem
i nc or r ec t t o hav e c hi l d management oper at i ons i n t he l eav es (l i k e
add(), r emov e(), and get Chi l d()), b ut t hen agai n y ou c an al w ay s shi f t
y our per spec t i v e and see a l eaf as a node w i t h zer o c hi l dr en.
PAT T ER N S EXPO SED
This week’s interview: T he Composite Pattern, on implementation issues

HeadFirst: We’re here tonight speaking with the Composite Pattern. Why
don’t you tell us a little about yourself, Composite?

Composite: Sure...I’m the pattern to use when you have collections of


objects with whole-part relationships and you want to be able to treat those
objects uniformly.

HeadFirst: Okay, let’s dive right in here...what do you mean by whole-part


relationships?

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?

Composite: Right. I can tell a composite object to display or a leaf object


to display and it will do the right thing. T he composite object will display
by telling all its components to display.

HeadFirst: T hat implies that every object has the same interface. What if
you have objects in your composite that do different things?

Composite: In order for the composite to work transparently to the client,


you must implement the same interface for all objects in the composite;
otherwise, the client has to worry about which interface each object is
implementing, which kind of defeats the purpose. Obviously that means
that at times you’ll have objects for which some of the method calls don’t
make sense.

HeadFirst: So how do you handle that?

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: Usually it’s a tree structure, some kind of hierarchy. T he root is


the top-level composite, and all its children are either composites or
leaves.

HeadFirst: Do children ever point back up to their parents?

Composite: Yes, a component can have a pointer to a parent to make


traversal of the structure easier. And, if you have a reference to a child and
you need to delete it, you’ll need to get the parent to remove the child.
Having the parent reference makes that easier too.

HeadFirst: T here’s really quite a lot to consider in your implementation.


Are there other issues we should think about when implementing the
Composite Pattern?

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: A good point I hadn’t thought of.

Composite: And did you think about caching?

HeadFirst: Caching?

Composite: Yeah, caching. Sometimes, if the composite structure is


complex or expensive to traverse, it’s helpful to implement caching of the
composite nodes. For instance, if you are constantly traversing a
composite and all its children to compute some result, you could
implement a cache that stores the result temporarily to save traversals.

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.

HeadFirst: T hat does sound like an important benefit. T here’s no doubt


you’re a useful pattern to have around for collecting and managing objects.
And, with that, we’re out of time. T hanks so much for joining us and come
back soon for another Patterns Exposed.

Design Patterns Crossword


W r ap y our b r ai n ar ound t hi s c omposi t e c r ossw or d.
ACROSS

1 . Col l ec t i on and It er at or ar e i n t hi s pac k age.

3. Thi s c l ass i ndi r ec t l y suppor t s It er at or .

8. It er at or s ar e usual l y c r eat ed usi ng t hi s pat t er n (t w o w or ds).

1 2. A c l ass shoul d hav e onl y one r eason t o do t hi s.

1 3. W e enc apsul at ed t hi s.

1 5. U ser i nt er f ac e pac k ages of t en use t hi s pat t er n f or t hei r


c omponent s.

1 6. N ame of t he pr i nc i pl e t hat st at es onl y one r esponsi b i l i t y per


c l ass (t w o w or ds).

1 7 . Thi s menu c aused us t o c hange our ent i r e i mpl ement at i on.

DOWN

2. Has no c hi l dr en.

4. Mer ged w i t h t he Di ner (t w o w or ds).

5. The It er at or Pat t er n dec oupl es t he c l i ent f r om t he aggr egat e’s


________.

6. A separ at e ob jec t t hat c an t r av er se a c ol l ec t i on.

7 . HashMap v al ues and A r r ay Li st b ot h i mpl ement t hi s i nt er f ac e.

9. W e Jav a-enab l ed her .

1 0. A c omponent c an b e a c omposi t e or t hi s.

1 1 . A c omposi t e hol ds t hese.

1 2. Thi r d c ompany ac qui r ed.

1 4. W e del et ed t he Panc ak eHouseMenuIt er at or b ec ause t hi s c l ass


al r eady pr ov i des an i t er at or .

W H O D O ES W H AT ?
Match each pattern with its description:

Patte
rn Description

Strate Clients treat collections of objects and individual objects uniformly


gy

Adapt Provides a way to traverse a collection of objects without exposing the


er collection’s implementation

Iterat Simplifies the interface of a group of classes


or

Faca Changes the interface of one or more classes


de

Comp Allows a group of objects to be notified when some state changes


osite

Obser Encapsulates interchangeable behaviors and uses delegation to


ver decide which one to use

Tools for your Design Toolbox


Tw o new pat t er ns f or y our t ool b ox —t w o gr eat w ay s t o deal w i t h
c ol l ec t i ons of ob jec t s.
B U L L ET PO IN T S

An Iterator allows access to an aggregate’s elements without


exposing its internal structure.

An Iterator takes the job of iterating over an aggregate and


encapsulates it in another object.

When using an Iterator, we relieve the aggregate of the


responsibility of supporting operations for traversing its data.

An Iterator provides a common interface for traversing the items


of an aggregate, allowing you to use polymorphism when writing
code that makes use of the items of the aggregate.

T he Iterable interface provides a means of getting an iterator


and enables Java’s enchanced for loop.

We should strive to assign only one responsibility to each


class.

T he Composite Pattern allows clients to treat composites and


individual objects uniformly.

A Component is any object in a Composite structure.


Components may be other composites or leaves.

T here are many design tradeoffs in implementing Composite.


You need to balance transparency and safety with your needs.

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?

A. We are coding to the PancakeHouseMenu and DinerMenu


concrete implementations, not to an interface.

B. T he Waitress doesn’t implement the Java Waitress API and so


she isn’t adhering to a standard.

C. If we decided to switch from using DinerMenu to another type of


menu that implemented its list of menu items with a hash table, we’d have
to modify a lot of code in the Waitress.

D. T he Waitress needs to know how each menu represents its


internal collection of menu items; this violates encapsulation.

E. We have duplicate code: the printMenu() method needs two


separate loops to iterate over the two different kinds of menus. And if we
added a third menu, we’d have yet another loop.

F. T he implementation isn’t based on MXML (Menu XML) and so isn’t


as interoperable as it should be.
SH AR PEN YO U R PEN C IL
SO L U T IO N
Before looking at the next page, quickly jot down the three things we have
to do to this code to fit it into our framework:

1. implement the Menu interface

2. get rid of getItems()

3. add createIterator() and return an Iterator that can step through the
HashMap values

Code Magnets Solution

The unsc r amb l ed “A l t er nat i ng” Di ner Menu It er at or .

W H O D O ES W H AT ?
Match each pattern with its description:

Design Patterns Crossword Solution


W r ap y our b r ai n ar ound t hi s c omposi t e c r ossw or d. Her e’s our
sol ut i on.
Chapter 10. The State of Things:
The State Pattern

A little-known fact: the Strategy and State Patterns are twins


separated at birth. You’d t hi nk t hey ’d l i v e si mi l ar l i v es, b ut t he
St r at egy Pat t er n w ent on t o c r eat e a w i l dl y suc c essf ul b usi ness
ar ound i nt er c hangeab l e al gor i t hms, w hi l e St at e t ook t he per haps
mor e nob l e pat h of hel pi ng ob jec t s t o c ont r ol t hei r b ehav i or b y
c hangi ng t hei r i nt er nal st at e. A s di f f er ent as t hei r pat hs b ec ame,
how ev er , under neat h y ou’l l f i nd al most pr ec i sel y t he same desi gn.
How c an t hat b e? A s y ou’l l see, St r at egy and St at e hav e v er y
di f f er ent i nt ent s. Fi r st , l et ’s di g i n and see w hat t he St at e Pat t er n i s
al l ab out , and t hen w e’l l r et ur n t o ex pl or e t hei r r el at i onshi p at t he
end of t he c hapt er .

Java Breakers

Gumb al l mac hi nes hav e gone hi gh t ec h. That ’s r i ght , t he major


manuf ac t ur er s hav e f ound t hat b y put t i ng CPU s i nt o t hei r c andy
mac hi nes, t hey c an i nc r ease sal es, moni t or i nv ent or y ov er t he
net w or k , and measur e c ust omer sat i sf ac t i on mor e ac c ur at el y .

But t hese manuf ac t ur er s ar e gumb al l mac hi ne ex per t s, not


sof t w ar e dev el oper s, and t hey ’v e ask ed f or y our hel p:

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.

Joe: Ri ght , eac h of t hose c i r c l es i s a st at e...

Judy : ...and eac h of t he ar r ow s i s a st at e t r ansi t i on.

F rank: Sl ow dow n, y ou t w o, i t ’s b een t oo l ong si nc e I st udi ed st at e


di agr ams. Can y ou r emi nd me w hat t hey ’r e al l ab out ?

Judy : Sur e, Fr ank . Look at t he c i r c l es; t hose ar e st at es. “N o Quar t er ”


i s pr ob ab l y t he st ar t i ng st at e f or t he gumb al l mac hi ne b ec ause i t ’s
just si t t i ng t her e w ai t i ng f or y ou t o put y our quar t er i n. A l l st at es
ar e just di f f er ent c onf i gur at i ons of t he mac hi ne t hat b ehav e i n a
c er t ai n w ay and need some ac t i on t o t ak e t hem t o anot her st at e.

Joe: Ri ght . See, t o go t o anot her st at e, y ou need t o do somet hi ng l i k e


put a quar t er i n t he mac hi ne. See t he ar r ow f r om “N o Quar t er ” t o
“Has Quar t er ”?

F rank: Yes...

Joe: That just means t hat i f t he gumb al l mac hi ne i s i n t he “N o


Quar t er ” st at e and y ou put a quar t er i n, i t w i l l c hange t o t he “Has
Quar t er ” st at e. That ’s t he st at e t r ansi t i on.

F rank: Oh, I see! A nd i f I’m i n t he “Has Quar t er ” st at e, I c an t ur n t he


c r ank and c hange t o t he “Gumb al l Sol d” st at e, or ejec t t he quar t er
and c hange b ac k t o t he “N o Quar t er ” st at e.

Judy : You got i t !

F rank: Thi s doesn’t l ook t oo b ad t hen. W e’v e ob v i ousl y got f our


st at es, and I t hi nk w e al so hav e f our ac t i ons: “i nser t quar t er ,” “ejec t
quar t er ,” “t ur n c r ank ,” and “di spense.” But ...w hen w e di spense, w e
t est f or zer o or mor e gumb al l s i n t he “Gumb al l Sol d” st at e, and t hen
ei t her go t o t he “Out of Gumb al l s” st at e or t he “N o Quar t er ” st at e.
So w e ac t ual l y hav e f i v e t r ansi t i ons f r om one st at e t o anot her .

Judy : That t est f or zer o or mor e gumb al l s al so i mpl i es w e’v e got t o


k eep t r ac k of t he numb er of gumb al l s t oo. A ny t i me t he mac hi ne
gi v es y ou a gumb al l , i t mi ght b e t he l ast one, and i f i t i s, w e need t o
t r ansi t i on t o t he “Out of Gumb al l s” st at e.

Joe: A l so, don’t f or get t hat y ou c oul d do nonsensi c al t hi ngs, l i k e t r y


t o ejec t t he quar t er w hen t he gumb al l mac hi ne i s i n t he “N o
Quar t er ” st at e, or i nser t t w o quar t er s.

F rank: Oh, I di dn’t t hi nk of t hat ; w e’l l hav e t o t ak e c ar e of t hose t oo.

Joe: For ev er y possi b l e ac t i on w e’l l just hav e t o c hec k t o see w hi c h


st at e w e’r e i n and ac t appr opr i at el y . W e c an do t hi s! Let ’s st ar t
mappi ng t he st at e di agr am t o c ode...

State machines 101


How ar e w e goi ng t o get f r om t hat st at e di agr am t o ac t ual c ode?
Her e’s a qui c k i nt r oduc t i on t o i mpl ement i ng st at e mac hi nes:

1 . Fi r st , gat her up y our st at es:

2. N ex t , c r eat e an i nst anc e v ar i ab l e t o hol d t he c ur r ent


st at e, and def i ne v al ues f or eac h of t he st at es:

3. N ow w e gat her up al l t he ac t i ons t hat c an happen i n t he


sy st em:
4. N ow w e c r eat e a c l ass t hat ac t s as t he st at e mac hi ne. For
eac h ac t i on, w e c r eat e a met hod t hat uses c ondi t i onal
st at ement s t o det er mi ne w hat b ehav i or i s appr opr i at e i n
eac h st at e. For i nst anc e, f or t he “i nser t quar t er ” ac t i on,
w e mi ght w r i t e a met hod l i k e t hi s:

W i t h t hat qui c k r ev i ew , l et ’s go i mpl ement t he Gumb al l


Mac hi ne!

Writing the code


It ’s t i me t o i mpl ement t he Gumb al l Mac hi ne. W e k now w e’r e goi ng
t o hav e an i nst anc e v ar i ab l e t hat hol ds t he c ur r ent st at e. Fr om
t her e, w e just need t o handl e al l t he ac t i ons, b ehav i or s, and st at e
t r ansi t i ons t hat c an happen. For ac t i ons, w e need t o i mpl ement
i nser t i ng a quar t er , r emov i ng a quar t er , t ur ni ng t he c r ank , and
di spensi ng a gumb al l ; w e al so hav e t he empt y Gumb al l Mac hi ne
c ondi t i on t o i mpl ement .
In-house testing
That f eel s l i k e a ni c e sol i d desi gn usi ng a w el l -t hought -out
met hodol ogy , doesn’t i t ? Let ’s do a l i t t l e i n-house t est i ng b ef or e w e
hand i t of f t o Mi ght y Gumb al l t o b e l oaded i nt o t hei r ac t ual
gumb al l mac hi nes. Her e’s our t est har ness:

You knew it was coming...a change request!


Mighty Gumball, I nc., has loaded y our code into their newest
machine and their quality assurance experts are putting it
through its paces. So far, ev ery thing’s looking great from their
perspectiv e.

I n fact, things hav e gone so smoothly they ’d like to take things


to the next lev el...

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.)

A. T his code certainly isn’t adhering to the Open Closed Principle.

B. T his code would make a FORT RAN programmer proud.

C. T his design isn’t even very object-oriented.

D. State transitions aren’t explicit; they are buried in the middle of a


bunch of conditional statements.

E. We haven’t encapsulated anything that varies here.

F. Further additions are likely to cause bugs in working code.

F rank: You’r e r i ght ab out t hat ! W e need t o r ef ac t or t hi s c ode so


t hat i t ’s easy t o mai nt ai n and modi f y .

Judy : W e r eal l y shoul d t r y t o l oc al i ze t he b ehav i or f or eac h st at e


so t hat i f w e mak e c hanges t o one st at e, w e don’t r un t he r i sk of
messi ng up t he ot her c ode.

F rank: Ri ght ; i n ot her w or ds, f ol l ow t hat ol ’ “enc apsul at e w hat


v ar i es” pr i nc i pl e.

Judy : Ex ac t l y .

F rank: If w e put eac h st at e’s b ehav i or i n i t s ow n c l ass, t hen ev er y


st at e just i mpl ement s i t s ow n ac t i ons.
Judy : Ri ght . A nd may b e t he Gumb al l Mac hi ne c an just del egat e t o
t he st at e ob jec t t hat r epr esent s t he c ur r ent st at e.

F rank: A h, y ou’r e good: f av or c omposi t i on...mor e pr i nc i pl es at


w or k .

Judy : Cut e. W el l , I’m not 1 00% sur e how t hi s i s goi ng t o w or k , b ut I


t hi nk w e’r e on t o somet hi ng.

F rank: I w onder i f t hi s w i l l mak e i t easi er t o add new st at es?

Judy : I t hi nk so... W e’l l st i l l hav e t o c hange c ode, b ut t he c hanges


w i l l b e muc h mor e l i mi t ed i n sc ope b ec ause addi ng a new st at e w i l l
mean w e just hav e t o add a new c l ass and may b e c hange a f ew
t r ansi t i ons her e and t her e.

F rank: I l i k e t he sound of t hat . Let ’s st ar t hashi ng out t hi s new


desi gn!

The new design


It l ook s l i k e w e’v e got a new pl an: i nst ead of mai nt ai ni ng our
ex i st i ng c ode, w e’r e goi ng t o r ew or k i t t o enc apsul at e st at e ob jec t s
i n t hei r ow n c l asses and t hen del egat e t o t he c ur r ent st at e w hen an
ac t i on oc c ur s.

W e’r e f ol l ow i ng our desi gn pr i nc i pl es her e, so w e shoul d end up


w i t h a desi gn t hat i s easi er t o mai nt ai n dow n t he r oad. Her e’s how
w e’r e goi ng t o do i t :

1 . F irst, we’re going to define a State interface that


contains a method for ev ery action in the Gumball
Machine.

2. Then we’re going to implement a State class for ev ery


state of the machine. These classes will be responsible
for the behav ior of the machine when it is in the
corresponding state.

3. F inally , we’re going to get rid of all of our conditional


code and instead delegate the work to the State class.

N ot onl y ar e w e f ol l ow i ng desi gn pr i nc i pl es, as y ou’l l see, w e’r e


ac t ual l y i mpl ement i ng t he St at e Pat t er n. But w e’l l get t o al l t he
of f i c i al St at e Pat t er n st uf f af t er w e r ew or k our c ode...

Defining the State interfaces and classes


Fi r st l et ’s c r eat e an i nt er f ac e f or St at e, w hi c h al l our st at es
i mpl ement :

Then t ak e eac h st at e i n our desi gn and enc apsul at e i t i n a c l ass t hat


i mpl ement s t he St at e i nt er f ac e.
SH AR PEN YO U R PEN C IL
To implement our states, we first need to specify the behavior of the
classes when each action is called. Annotate the diagram below with the
behavior of each action in each class; we’ve already filled in a few for you.

Implementing our State classes


Ti me t o i mpl ement a st at e: w e k now w hat b ehav i or s w e w ant ; w e
just need t o get i t dow n i n c ode. W e’r e goi ng t o c l osel y f ol l ow t he
st at e mac hi ne c ode w e w r ot e, b ut t hi s t i me ev er y t hi ng i s b r ok en
out i nt o di f f er ent c l asses.

Let ’s st ar t w i t h t he N oQuar t er St at e:

Reworking the Gumball Machine


Bef or e w e f i ni sh t he St at e c l asses, w e’r e goi ng t o r ew or k t he
Gumb al l Mac hi ne—t hat w ay , y ou c an see how i t al l f i t s t oget her .
W e’l l st ar t w i t h t he st at e-r el at ed i nst anc e v ar i ab l es and sw i t c h t he
c ode f r om usi ng i nt eger s t o usi ng st at e ob jec t s:
Now, let’s look at the complete GumballMachine class...

Implementing more states


N ow t hat y ou’r e st ar t i ng t o get a f eel f or how t he Gumb al l Mac hi ne
and t he st at es f i t t oget her , l et ’s i mpl ement t he HasQuar t er St at e and
t he Sol dSt at e c l asses...

N ow , l et ’s c hec k out t he Sol dSt at e c l ass...

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...

public class SoldOutState implements _______________ {


GumballMachine gumballMachine;

public SoldOutState(GumballMachine gumballMachine)


{

public void insertQuarter() {

public void ejectQuarter() {

public void turnCrank() {

public void dispense() {

}
}

Let’s take a look at what we’ve done so far...


For st ar t er s, y ou now hav e a Gumb al l Mac hi ne i mpl ement at i on
t hat i s s truc turally qui t e di f f er ent f r om y our f i r st v er si on, and y et
func tionally it is exac tly th e s am e. By st r uc t ur al l y c hangi ng t he
i mpl ement i on, y ou’v e:

Loc al i zed t he b ehav i or of eac h st at e i nt o i t s ow n c l ass.

Remov ed al l t he t r oub l esome i f st at ement s t hat w oul d


hav e b een di f f i c ul t t o mai nt ai n.

Cl osed eac h st at e f or modi f i c at i on, and y et l ef t t he


Gumb al l Mac hi ne open t o ex t ensi on b y addi ng new st at e
c l asses (and w e’l l do t hi s i n a sec ond).

Cr eat ed a c ode b ase and c l ass st r uc t ur e t hat maps muc h


mor e c l osel y t o t he Mi ght y Gumb al l di agr am and i s easi er
t o r ead and under st and.

N ow l et ’s l ook a l i t t l e mor e at t he f unc t i onal aspec t of w hat w e di d:


SH AR PEN YO U R PEN C IL

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.

The State Pattern defined


Yes, i t ’s t r ue, w e just i mpl ement ed t he St at e Pat t er n! So now , l et ’s
t ak e a l ook at w hat i t ’s al l ab out :

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.

The f i r st par t of t hi s desc r i pt i on mak es a l ot of sense, r i ght ?


Bec ause t he pat t er n enc apsul at es st at e i nt o separ at e c l asses and
del egat es t o t he ob jec t r epr esent i ng t he c ur r ent st at e, w e k now
t hat b ehav i or c hanges al ong w i t h t he i nt er nal st at e. The Gumb al l
Mac hi ne pr ov i des a good ex ampl e: w hen t he gumb al l mac hi ne i s i n
t he N oQuar t er St at e and y ou i nser t a quar t er , y ou get di f f er ent
b ehav i or (t he mac hi ne ac c ept s t he quar t er ) t han i f y ou i nser t a
quar t er w hen i t ’s i n t he HasQuar t er St at e (t he mac hi ne r ejec t s t he
quar t er ).

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.

Ok ay , now i t ’s t i me t o c hec k out t he St at e Pat t er n c l ass di agr am:

You’v e got a good ey e (or y ou r ead t he b egi nni ng of t he c hapt er )!


Yes, t he c l ass di agr ams ar e essent i al l y t he same, b ut t he t w o
pat t er ns di f f er i n t hei r intent.

W i t h t he St at e Pat t er n, w e hav e a set of b ehav i or s enc apsul at ed i n


st at e ob jec t s; at any t i me t he c ont ex t i s del egat i ng t o one of t hose
st at es. Ov er t i me, t he c ur r ent st at e c hanges ac r oss t he set of st at e
ob jec t s t o r ef l ec t t he i nt er nal st at e of t he c ont ex t , so t he c ont ex t ’s
b ehav i or c hanges ov er t i me as w el l . The c l i ent usual l y k now s v er y
l i t t l e, i f any t hi ng, ab out t he st at e ob jec t s.

W i t h St r at egy , t he c l i ent usual l y spec i f i es t he st r at egy ob jec t t hat


t he c ont ex t i s c omposed w i t h. N ow , w hi l e t he pat t er n pr ov i des t he
f l ex i b i l i t y t o c hange t he st r at egy ob jec t at r unt i me, of t en t her e i s
a st r at egy ob jec t t hat i s most appr opr i at e f or a c ont ex t ob jec t . For
i nst anc e, i n Chapt er 1 , some of our duc k s w er e c onf i gur ed t o f l y
w i t h t y pi c al f l y i ng b ehav i or (l i k e mal l ar d duc k s), w hi l e ot her s
w er e c onf i gur ed w i t h a f l y b ehav i or t hat k ept t hem gr ounded (l i k e
r ub b er duc k s and dec oy duc k s).

In gener al , t hi nk of t he St r at egy Pat t er n as a f l ex i b l e al t er nat i v e


t o sub c l assi ng; i f y ou use i nher i t anc e t o def i ne t he b ehav i or of a
c l ass, t hen y ou’r e st uc k w i t h t hat b ehav i or ev en i f y ou need t o
c hange i t . W i t h St r at egy y ou c an c hange t he b ehav i or b y
c omposi ng w i t h a di f f er ent ob jec t .

Thi nk of t he St at e Pat t er n as an al t er nat i v e t o put t i ng l ot s of


c ondi t i onal s i n y our c ont ex t ; b y enc apsul at i ng t he b ehav i or s
w i t hi n st at e ob jec t s, y ou c an si mpl y c hange t he st at e ob jec t i n
c ont ex t t o c hange i t s b ehav i or .

there are no Dumb Questions


Q: I n GumballMachine, the states decide what the next state
should be. Do the ConcreteStates alway s decide what state to
go to next?

A: N o, not al w ay s. The al t er nat i v e i s t o l et t he Cont ex t dec i de on


t he f l ow of st at e t r ansi t i ons.

A s a gener al gui del i ne, w hen t he st at e t r ansi t i ons ar e f i x ed t hey


ar e appr opr i at e f or put t i ng i n t he Cont ex t ; how ev er , w hen t he
t r ansi t i ons ar e mor e dy nami c , t hey ar e t y pi c al l y pl ac ed i n t he
st at e c l asses t hemsel v es (f or i nst anc e, i n Gumb al l Mac hi ne t he
c hoi c e of t he t r ansi t i on t o N oQuar t er or Sol dOut depended on t he
r unt i me c ount of gumb al l s).

The di sadv ant age of hav i ng st at e t r ansi t i ons i n t he st at e c l asses i s


t hat w e c r eat e dependenc i es b et w een t he st at e c l asses. In our
i mpl ement at i on of Gumb al l Mac hi ne w e t r i ed t o mi ni mi ze t hi s b y
usi ng get t er met hods on t he Cont ex t , r at her t han har dc odi ng
ex pl i c i t c onc r et e st at e c l asses.
N ot i c e t hat b y mak i ng t hi s dec i si on, y ou ar e mak i ng a dec i si on as t o
w hi c h c l asses ar e c l osed f or modi f i c at i on—t he Cont ex t or t he st at e
c l asses—as t he sy st em ev ol v es.

Q: Do clients ev er interact directly with the states?

A: N o. The st at es ar e used b y t he Cont ex t t o r epr esent i t s i nt er nal


st at e and b ehav i or , so al l r equest s t o t he st at es c ome f r om t he
Cont ex t . Cl i ent s don’t di r ec t l y c hange t he st at e of t he Cont ex t . It i s
t he Cont ex t ’s job t o ov er see i t s st at e, and y ou don’t usual l y w ant a
c l i ent c hangi ng t he st at e of a Cont ex t w i t hout t hat Cont ex t ’s
k now l edge.

Q: I f I hav e lots of instances of the Context in my application, is


it possible to share the state obj ects across them?

A: Yes, ab sol ut el y , and i n f ac t t hi s i s a v er y c ommon sc enar i o. The


onl y r equi r ement i s t hat y our st at e ob jec t s do not k eep t hei r ow n
i nt er nal c ont ex t ; ot her w i se, y ou’d need a uni que i nst anc e per
c ont ex t .

To shar e y our st at es, y ou’l l t y pi c al l y assi gn eac h st at e t o a st at i c


i nst anc e v ar i ab l e. If y our st at e needs t o mak e use of met hods or
i nst anc e v ar i ab l es i n y our Cont ex t , y ou’l l al so hav e t o gi v e i t a
r ef er enc e t o t he Cont ex t i n eac h handl er () met hod.

Q: I t seems like using the State Pattern alway s increases the


number of classes in our designs. Look how many more classes
our GumballMachine had than the original design!

A: You’r e r i ght ; b y enc apsul at i ng st at e b ehav i or i nt o separ at e st at e


c l asses, y ou’l l al w ay s end up w i t h mor e c l asses i n y our desi gn.
That ’s of t en t he pr i c e y ou pay f or f l ex i b i l i t y . U nl ess y our c ode i s
some “one-of f ” i mpl ement at i on y ou’r e goi ng t o t hr ow aw ay (y eah,
r i ght ), c onsi der b ui l di ng i t w i t h t he addi t i onal c l asses and y ou’l l
pr ob ab l y t hank y our sel f dow n t he r oad. N ot e t hat of t en w hat i s
i mpor t ant i s t he numb er of c l asses t hat y ou ex pose t o y our c l i ent s,
and t her e ar e w ay s t o hi de t hese ex t r a c l asses f r om y our c l i ent s
(say , b y dec l ar i ng t hem pac k age pr i v at e).

A l so, c onsi der t he al t er nat i v e: i f y ou hav e an appl i c at i on t hat has a


l ot of st at e and y ou dec i de not t o use separ at e ob jec t s, y ou’l l i nst ead
end up w i t h v er y l ar ge, monol i t hi c c ondi t i onal st at ement s. Thi s
mak es y our c ode har d t o mai nt ai n and under st and. By usi ng ob jec t s,
y ou mak e st at es ex pl i c i t and r educ e t he ef f or t needed t o under st and
and mai nt ai n y our c ode.

Q: The State Pattern class diagram shows that State is an


abstract class. But didn’t y ou use an interface in the
implementation of the gumball machine’s state?

A: Yes. Gi v en w e had no c ommon f unc t i onal i t y t o put i nt o an


ab st r ac t c l ass, w e w ent w i t h an i nt er f ac e. In y our ow n
i mpl ement at i on, y ou mi ght w ant t o c onsi der an ab st r ac t c l ass.
Doi ng so has t he b enef i t of al l ow i ng y ou t o add met hods t o t he
ab st r ac t c l ass l at er , w i t hout b r eak i ng t he c onc r et e st at e
i mpl ement at i ons.

We still need to finish the Gumball 1 in 10 game


Rememb er , w e’r e not done y et . W e’v e got a game t o i mpl ement , b ut
now t hat w e’v e got t he St at e Pat t er n i mpl ement ed, i t shoul d b e a
b r eeze. Fi r st , w e need t o add a st at e t o t he Gumb al l Mac hi ne c l ass:

N ow l et ’s i mpl ement t he W i nner St at e c l ass; i t ’s r emar k ab l y


si mi l ar t o t he Sol dSt at e c l ass:

Finishing the game


W e’v e got just one mor e c hange t o mak e: w e need t o i mpl ement t he
r andom c hanc e game and add a t r ansi t i on t o t he W i nner St at e. W e’r e
goi ng t o add b ot h t o t he HasQuar t er St at e si nc e t hat ’s w her e t he
c ust omer t ur ns t he c r ank :
W ow , t hat w as pr et t y si mpl e t o i mpl ement ! W e just added a new
st at e t o t he Gumb al l Mac hi ne and t hen i mpl ement ed i t . A l l w e had
t o do f r om t her e w as t o i mpl ement our c hanc e game and t r ansi t i on
t o t he c or r ec t st at e. It l ook s l i k e our new c ode st r at egy i s pay i ng
of f ...

Demo for the CEO of Mighty Gumball, Inc.


The CEO of Mi ght y Gumb al l has dr opped b y f or a demo of y our new
gumb al l game c ode. Let ’s hope t hose st at es ar e al l i n or der ! W e’l l
k eep t he demo shor t and sw eet (t he shor t at t ent i on span of CEOs i s
w el l doc ument ed), b ut hopef ul l y l ong enough so t hat w e’l l w i n at
l east onc e.

there are no Dumb Questions


Q: Why do we need the WinnerState? Couldn’t we j ust hav e the
SoldState dispense two gumballs?

A: That ’s a gr eat quest i on. Sol dSt at e and W i nner St at e ar e al most


i dent i c al , ex c ept t hat W i nner St at e di spenses t w o gumb al l s i nst ead
of one. You c er t ai nl y c oul d put t he c ode t o di spense t w o gumb al l s
i nt o Sol dSt at e. The dow nsi de i s, of c our se, t hat now y ou’v e got TW O
st at es r epr esent ed i n one St at e c l ass: t he st at e i n w hi c h y ou’r e a
w i nner , and t he st at e i n w hi c h y ou’r e not . So y ou ar e sac r i f i c i ng
c l ar i t y i n y our St at e c l ass t o r educ e c ode dupl i c at i on. A not her
t hi ng t o c onsi der i s t he pr i nc i pl e y ou l ear ned i n t he pr ev i ous
c hapt er : t he Si ngl e Responsi b i l i t y Pr i nc i pl e. By put t i ng t he
W i nner St at e r esponsi b i l i t y i nt o t he Sol dSt at e, y ou’v e just gi v en
t he Sol dSt at e TW O r esponsi b i l i t i es. W hat happens w hen t he
pr omot i on ends? Or t he st ak es of t he c ont est c hange? So, i t ’s a
t r adeof f and c omes dow n t o a desi gn dec i si on.

Sanity check...

Yes, t he CEO of Mi ght y Gumb al l pr ob ab l y needs a sani t y c hec k , b ut


t hat ’s not w hat w e’r e t al k i ng ab out her e. Let ’s t hi nk t hr ough some
aspec t s of t he Gumb al l Mac hi ne t hat w e mi ght w ant t o shor e up
b ef or e w e shi p t he gol d v er si on:

W e’v e got a l ot of dupl i c at e c ode i n t he Sol d and W i nni ng


st at es and w e mi ght w ant t o c l ean t hose up. How w oul d w e
do i t ? W e c oul d mak e St at e i nt o an ab st r ac t c l ass and
b ui l d i n some def aul t b ehav i or f or t he met hods; af t er al l ,
er r or messages l i k e, “You al r eady i nser t ed a quar t er ,”
ar en’t goi ng t o b e seen b y t he c ust omer . So al l “er r or
r esponse” b ehav i or c oul d b e gener i c and i nher i t ed f r om
t he ab st r ac t St at e c l ass.

N O TE
Dammit Jim, I’m a gumball machine, not a
computer!

The di spense() met hod al w ay s get s c al l ed, ev en i f t he


c r ank i s t ur ned w hen t her e i s no quar t er . W hi l e t he
mac hi ne oper at es c or r ec t l y and doesn’t di spense unl ess
i t ’s i n t he r i ght st at e, w e c oul d easi l y f i x t hi s b y hav i ng
t ur nCr ank () r et ur n a b ool ean or b y i nt r oduc i ng
ex c ept i ons. W hi c h do y ou t hi nk i s a b et t er sol ut i on?

A l l of t he i nt el l i genc e f or t he st at e t r ansi t i ons i s i n t he


St at e c l asses. W hat pr ob l ems mi ght t hi s c ause? W oul d w e
w ant t o mov e t hat l ogi c i nt o t he Gumb al l Mac hi ne? W hat
w oul d b e t he adv ant ages and di sadv ant ages of t hat ?

W i l l y ou b e i nst ant i at i ng a l ot of Gumb al l Mac hi ne


ob jec t s? If so, y ou may w ant t o mov e t he st at e i nst anc es
i nt o st at i c i nst anc e v ar i ab l es and shar e t hem. W hat
c hanges w oul d t hi s r equi r e t o t he Gumb al l Mac hi ne and
t he St at es?

Toni ght ’s t al k : A Strategy and State Pattern Reunion.


Strategy: State:

Hey, bro. Did you hear I was in


Chapter 1?

Yeah, word is definitely getting around.

I was just over giving the


Template Method guys a hand—
they needed me to help them
finish off their chapter. So,
anyway, what is my noble
brother up to?

Same as always—helping classes to exhibit different


behaviors in different states.

I don’t know, you always sound


like you’ve just copied what I do
and you’re using different words
to describe it. Think about it: I
allow objects to incorporate
different behaviors or algorithms
through composition and
delegation. You’re just copying
me.

I admit that what we do is definitely related, but my


intent is totally different than yours. And the way I
teach my clients to use composition and delegation
is totally different.

Oh yeah? How so? I don’t get it.

Well, if you spent a little more time thinking about


something other than yourself, you might. Anyway,
think about how you work: you have a class you’re
instantiating and you usually give it a strategy
object that implements some behavior. Like, in
Chapter 1 you were handing out quack behaviors,
right? Real ducks got a real quack; rubber ducks
got a quack that squeaked.

Yeah, that was some fine


work...and I’m sure you can see
how that’s more powerful than
inheriting your behavior, right?

Yes, of course. Now, think about how I work; it’s


totally different.

Sorry, you’re going to have to


explain that.

Okay, when my Context objects get created, I may


tell them the state to start in, but then they change
their own state over time.

Hey, come on, I can change


behavior at runtime too; that’s
what composition is all about!

Sure you can, but the way I work is built around


discrete states; my Context objects change state over
time according to some well-defined state
transitions. In other words, changing behavior is
built in to my scheme—it’s how I work!

Well, I admit, I don’t encourage


my objects to have a well-defined
set of transitions between states.
In fact, I typically like to control
what strategy my objects are
using.

Look, we’ve already said we’re alike in structure,


but what we do is quite different in intent. Face it,
the world has uses for both of us.

Yeah, yeah, keep living your pipe


dreams, brother. You act like
you’re a big pattern like me, but
check it out: I’m in Chapter 1;
they stuck you way out in
Chapter 10. I mean, how many
people are actually going to read
this far?

Are you kidding? This is a Head First book and


Head First readers rock. Of course they’re going to
get to Chapter 10!

That’s my brother, always the


dreamer.

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

State Encapsulate interchangeable behaviors and use delegation to


decide which behavior to use.

Strategy Subclasses decide how to implement steps in an algorithm.

Template Encapsulate state-based behavior and delegate behavior to the


Method current state.

Tools for your Design Toolbox


It ’s t he end of anot her c hapt er ; y ou’v e got enough pat t er ns her e t o
b r eeze t hr ough any job i nt er v i ew !
B U L L ET PO IN T S

T he State Pattern allows an object to have many different


behaviors that are based on its internal state.

Unlike a procedural state machine, the State Pattern represents


each state as a full-blown class.

T he Context gets its behavior by delegating to the current state


object it is composed with.

By encapsulating each state into a class, we localize any


changes that will need to be made.

T he State and Strategy Patterns have the same class diagram,


but they differ in intent.

T he Strategy Pattern typically configures Context classes with a


behavior or algorithm.

T he State Pattern allows a Context to change its behavior as


the state of the Context changes.

State transitions can be controlled by the State classes or by


the Context classes.

Using the State Pattern will typically result in a greater number


of classes in your design.

State classes may be shared among Context instances.

Design Puzzle Solution


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. Her e’s our sol ut i on.

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.

A. T his code certainly isn’t adhering to the Open Closed Principle.

B. T his code would make a FORT RAN programmer proud.

C. T his design isn’t even very object-oriented.

D. State transitions aren’t explicit; they are buried in the middle of a


bunch of conditional statements.

E. We haven’t encapsulated anything that varies here.

F. Further additions are likely to cause bugs in working code.


SH AR PEN YO U R PEN C IL
SO L U T IO N
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. Here’s our solution.

N OT E
In the Sold Out state, we really can’t do anything until someone refills
the Gumball Machine.

public class SoldOutState implements State {


GumballMachine gumballMachine;

public SoldOutState(GumballMachine gumballMachine)


{
this.gumballMachine = gumballMachine;
}

public void insertQuarter() {


System.out.println("You can't insert a
quarter, the machine is sold out");
}

public void ejectQuarter() {


System.out.println("You can't eject, you
haven't inserted a quarter yet");
}

public void turnCrank() {


System.out.println("You turned, but there are
no gumballs");
}

public void dispense() {


System.out.println("No gumball dispensed");
}
}

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

Ev er play good cop, bad cop? You’r e t he good c op and y ou pr ov i de


al l y our ser v i c es i n a ni c e and f r i endl y manner , b ut y ou don’t w ant
ev er y one ask i ng y ou f or ser v i c es, so y ou hav e t he b ad c op c ont r ol
ac c ess t o y ou. That ’s w hat pr ox i es do: c ont r ol and manage ac c ess. A s
y ou’r e goi ng t o see, t her e ar e l ot s of w ay s i n w hi c h pr ox i es st and i n
f or t he ob jec t s t hey pr ox y . Pr ox i es hav e b een k now n t o haul ent i r e
met hod c al l s ov er t he i nt er net f or t hei r pr ox i ed ob jec t s; t hey ’v e
al so b een k now n t o pat i ent l y st and i n f or some pr et t y l azy ob jec t s.

Sounds easy enough. If y ou r ememb er , w e’v e al r eady got met hods i n


t he gumb al l mac hi ne c ode f or get t i ng t he c ount of gumb al l s,
get Count (), and get t i ng t he c ur r ent st at e of t he mac hi ne, get St at e().

A l l w e need t o do i s c r eat e a r epor t t hat c an b e pr i nt ed out and sent


b ac k t o t he CEO. Hmmm, w e shoul d pr ob ab l y add a l oc at i on f i el d t o
eac h gumb al l mac hi ne as w el l ; t hat w ay t he CEO c an k eep t he
mac hi nes st r ai ght .

Let ’s just jump i n and c ode t hi s. W e’l l i mpr ess t he CEO w i t h a v er y


f ast t ur nar ound.

Coding the Monitor


Let ’s st ar t b y addi ng suppor t t o t he Gumb al l Mac hi ne c l ass so t hat i t
c an handl e l oc at i ons:

N ow l et ’s c r eat e anot her c l ass, Gumb al l Moni t or , t hat r et r i ev es t he


mac hi ne’s l oc at i on, i nv ent or y of gumb al l s, and c ur r ent mac hi ne
st at e and pr i nt s t hem i n a ni c e l i t t l e r epor t :
Testing the Monitor
W e i mpl ement ed t hat i n no t i me. The CEO i s goi ng t o b e t hr i l l ed
and amazed b y our dev el opment sk i l l s.

N ow w e just need t o i nst ant i at e a Gumb al l Moni t or and gi v e i t a


mac hi ne t o moni t or :

F rank: A r emot e w hat ?

Joe: Remot e pr ox y . Thi nk ab out i t : w e’v e al r eady got t he moni t or


c ode w r i t t en, r i ght ? W e gi v e t he Gumb al l Moni t or c l ass a r ef er enc e
t o a mac hi ne and i t gi v es us a r epor t . The pr ob l em i s t hat t he
moni t or r uns i n t he same JV M as t he gumb al l mac hi ne and t he CEO
w ant s t o si t at hi s desk and r emot el y moni t or t he mac hi nes! So w hat
i f w e l ef t our Gumb al l Moni t or c l ass as i s, b ut handed i t a pr ox y t o a
r emot e ob jec t ?

F rank: I’m not sur e I get i t .

Jim: Me nei t her .

Joe: Let ’s st ar t at t he b egi nni ng...a pr ox y i s a st and i n f or a r eal


ob jec t . In t hi s c ase, t he pr ox y ac t s just l i k e i t i s a Gumb al l Mac hi ne
ob jec t , b ut b ehi nd t he sc enes i t i s c ommuni c at i ng ov er t he net w or k
t o t al k t o t he r eal , r emot e Gumb al l Mac hi ne.

Jim: So y ou’r e say i ng w e k eep our c ode as i t i s, and w e gi v e t he


moni t or a r ef er enc e t o a pr ox y v er si on of t he Gumb al l Mac hi ne...

F rank: A nd t hi s pr ox y pr et ends i t ’s t he r eal ob jec t , b ut i t ’s r eal l y


just c ommuni c at i ng ov er t he net t o t he r eal ob jec t .

Joe: Yeah, t hat ’s pr et t y muc h t he st or y .

F rank: It sounds l i k e somet hi ng t hat ’s easi er sai d t han done.

Joe: Per haps, b ut I don’t t hi nk i t ’l l b e t hat b ad. W e hav e t o mak e


sur e t hat t he gumb al l mac hi ne c an ac t as a ser v i c e and ac c ept
r equest s ov er t he net w or k ; w e al so need t o gi v e our moni t or a w ay
t o get a r ef er enc e t o a pr ox y ob jec t , b ut w e’v e got some gr eat t ool s
al r eady b ui l t i nt o Jav a t o hel p us. Let ’s t al k a l i t t l e mor e ab out
r emot e pr ox i es f i r st ...

The role of the ‘remote proxy’

A r emot e pr ox y ac t s as a loc al repres entativ e to a rem ote objec t.


W hat ’s a “r emot e ob jec t ”? It ’s an ob jec t t hat l i v es i n t he heap of a
di f f er ent Jav a V i r t ual Mac hi ne (or mor e gener al l y , a r emot e ob jec t
t hat i s r unni ng i n a di f f er ent addr ess spac e). W hat ’s a “l oc al
r epr esent at i v e”? It ’s an ob jec t t hat y ou c an c al l l oc al met hods on
and hav e t hem f or w ar ded on t o t he r emot e ob jec t .
B R AIN PO W ER
Before going further, think about how you’d design a system to enable
Remote Method Invocation (RMI). How would you make it easy on the
developer so that she has to write as little code as possible? How would
you make the remote invocation look seamless?

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?

Adding a remote proxy to the Gumball Machine


monitoring code
On paper our pl an l ook s good, b ut how do w e c r eat e a pr ox y t hat
k now s how t o i nv ok e a met hod on an ob jec t t hat l i v es i n anot her
JV M?

Hmmm. W el l , y ou c an’t get a r ef er enc e t o somet hi ng on anot her


heap, r i ght ? In ot her w or ds, y ou c an’t say :

Duck d = <object in another heap>

W hat ev er t he v ar i ab l e d i s r ef er enc i ng must b e i n t he same heap


spac e as t he c ode r unni ng t he st at ement . So how do w e appr oac h
t hi s? W el l , t hat ’s w her e Jav a’s Remot e Met hod Inv oc at i on (RMI)
c omes i n...RMI gi v es us a w ay t o f i nd ob jec t s i n a r emot e JV M and
al l ow s us t o i nv ok e t hei r met hods.

N ow mi ght b e a good t i me t o b r ush up on RMI w i t h y our f av or i t e


Jav a r ef er enc e, or y ou c an t ak e t he RMI Detour ahead, and w e’l l
w al k y ou t hough t he hi gh poi nt s of RMI b ef or e addi ng t he pr ox y
suppor t t o t he Gumb al l Mac hi ne c ode.

In ei t her c ase, her e’s our pl an:

1 . F irst, we’re going to take the RMI Detour and explore


RMI . Ev en if y ou are familiar with RMI , y ou might
want to follow along and check out the scenery .

2. Then we’re going to take our Gumball Machine and


make it a remote serv ice that prov ides a set of
methods calls that can be inv oked remotely .

3. F inally , we going to create a proxy that can talk to a


remote Gumball Machine, again using RMI , and put
the monitoring sy stem back together so that the CEO
can monitor any number of remote machines.
Remote methods 101

Walking through the design


Let ’s say w e w ant t o desi gn a sy st em t hat al l ow s us t o c al l a l oc al
ob jec t t hat f or w ar ds eac h r equest t o a r emot e ob jec t . How w oul d w e
desi gn i t ? W e’d need a c oupl e of hel per ob jec t s t hat do t he
c ommuni c at i ng f or us. The hel per s mak e i t possi b l e f or t he c l i ent
t o ac t as t hough i t ’s c al l i ng a met hod on a l oc al ob jec t (w hi c h i t i s).
The c l i ent c al l s a met hod on t he c l i ent hel per , as i f t he c l i ent
hel per w er e t he ac t ual ser v i c e. The c l i ent hel per t hen t ak es c ar e
of f or w ar di ng t hat r equest f or us.

In ot her w or ds, t he c l i ent ob jec t t hi nk s i t ’s c al l i ng a met hod on t he


r emot e ser v i c e, b ec ause t he c l i ent hel per i s pr et endi ng t o b e t he
ser v i c e ob jec t —t hat i s, pr et endi ng t o b e t he t hi ng w i t h t he met hod
t he c l i ent w ant s t o c al l .

But t he c l i ent hel per i sn’t r eal l y t he r emot e ser v i c e. A l t hough t he


c l i ent hel per ac t s l i k e i t (b ec ause i t has t he same met hod t hat t he
ser v i c e i s adv er t i si ng), t he c l i ent hel per doesn’t hav e any of t he
met hod l ogi c t he c l i ent i s ex pec t i ng. Inst ead, t he c l i ent hel per
c ont ac t s t he ser v er , t r ansf er s i nf or mat i on ab out t he met hod c al l
(e.g., name of t he met hod, ar gument s, et c .), and w ai t s f or a r et ur n
f r om t he ser v er .

On t he ser v er si de, t he ser v i c e hel per r ec ei v es t he r equest f r om t he


c l i ent hel per (t hr ough a Soc k et c onnec t i on), unpac k s t he
i nf or mat i on ab out t he c al l , and t hen i nv ok es t he r eal met hod on t he
r eal ser v i c e ob jec t . So, t o t he ser v i c e ob jec t , t he c al l i s l oc al . It ’s
c omi ng f r om t he ser v i c e hel per , not a r emot e c l i ent .

The ser v i c e hel per get s t he r et ur n v al ue f r om t he ser v i c e, pac k s i t


up, and shi ps i t b ac k (ov er a Soc k et ’s out put st r eam) t o t he c l i ent
hel per . The c l i ent hel per unpac k s t he i nf or mat i on and r et ur ns t he
v al ue t o t he c l i ent ob jec t .

Let ’s w al k t hr ough t hi s t o mak e i t c l ear er ...

How the method call happens

1 . The Cl i ent ob jec t c al l s doBi gThi ng() on t he c l i ent hel per


ob jec t .

2. The Cl i ent hel per pac k ages up i nf or mat i on ab out t he c al l


(ar gument s, met hod name, et c .) and shi ps i t ov er t he
net w or k t o t he ser v i c e hel per .
3. The Ser v i c e hel per unpac k s t he i nf or mat i on f r om t he
c l i ent hel per , f i nds out w hi c h met hod t o c al l (and on
w hi c h ob jec t ), and i nv ok es t he r eal met hod on t he r eal
ser v i c e ob jec t .

4. The met hod i s i nv ok ed on t he ser v i c e ob jec t , w hi c h


r et ur ns some r esul t t o t he ser v i c e hel per .

5. The Ser v i c e hel per pac k ages up i nf or mat i on r et ur ned


f r om t he c al l and shi ps i t b ac k ov er t he net w or k t o t he
c l i ent hel per .

6. The Cl i ent hel per unpac k ages t he r et ur ned v al ues and


r et ur ns t hem t o t he c l i ent ob jec t . To t he c l i ent ob jec t ,
t hi s w as al l t r anspar ent .

Java RMI, the Big Picture


Ok ay , y ou’v e got t he gi st of how r emot e met hods w or k ; now y ou just
need t o under st and how t o use RMI.

W hat RMI does f or y ou i s b ui l d t he c l i ent and ser v i c e hel per


ob jec t s, r i ght dow n t o c r eat i ng a c l i ent hel per ob jec t w i t h t he same
met hods as t he r emot e ser v i c e. The ni c e t hi ng ab out RMI i s t hat y ou
don’t hav e t o w r i t e any of t he net w or k i ng or I/O c ode y our sel f .
W i t h y our c l i ent , y ou c al l r emot e met hods (i .e., t he ones t he Real
Ser v i c e has) just l i k e nor mal met hod c al l s on ob jec t s r unni ng i n t he
c l i ent ’s ow n l oc al JV M.

RMI al so pr ov i des al l t he r unt i me i nf r ast r uc t ur e t o mak e i t al l


w or k , i nc l udi ng a l ook up ser v i c e t hat t he c l i ent c an use t o f i nd and
ac c ess t he r emot e ob jec t s.

Ther e i s one di f f er enc e b et w een RMI c al l s and l oc al (nor mal )


met hod c al l s. Rememb er t hat ev en t hough t o t he c l i ent i t l ook s l i k e
t he met hod c al l i s l oc al , t he c l i ent hel per sends t he met hod c al l
ac r oss t he net w or k . So t her e i s net w or k i ng and I/O. A nd w hat do w e
k now ab out net w or k i ng and I/O met hods?

They ’r e r i sk y ! They c an f ai l ! A nd so t hey t hr ow ex c ept i ons al l ov er


t he pl ac e. A s a r esul t , t he c l i ent does hav e t o ac k now l edge t he r i sk .
W e’l l see how i n a f ew pages.

RMI nomenclature: in RMI , the client helper is a “stub” and the


serv ice helper is a “skeleton.”

N ow l et ’s go t hr ough al l t he st eps needed t o mak e an ob jec t i nt o a


ser v i c e t hat c an ac c ept r emot e c al l s and al so t he st eps needed t o
al l ow a c l i ent t o mak e r emot e c al l s.

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 .

Making the Remote service


Thi s i s an ov erv iew of t he f i v e st eps f or mak i ng t he r emot e ser v i c e
—i n ot her w or ds, t he st eps needed t o t ak e an or di nar y ob jec t and
super c har ge i t so i t c an b e c al l ed b y a r emot e c l i ent . W e’l l b e doi ng
t hi s l at er t o our Gumb al l Mac hi ne. For now , l et ’s get t he st eps dow n
and t hen w e’l l ex pl ai n eac h one i n det ai l .

Step one:

Mak e a Remote I nterface

The r emot e i nt er f ac e def i nes t he met hods t hat a c l i ent


c an c al l r emot el y . It ’s w hat t he c l i ent w i l l use as t he c l ass
t y pe f or y our ser v i c e. Bot h t he St ub and ac t ual ser v i c e
w i l l i mpl ement t hi s.

Step two:

Mak e a Remote I mplementation

Thi s i s t he c l ass t hat does t he Real W or k . It has t he r eal


i mpl ement at i on of t he r emot e met hods def i ned i n t he
r emot e i nt er f ac e. It ’s t he ob jec t t hat t he c l i ent w ant s t o
c al l met hods on (e.g., Gumb al l Mac hi ne).

Step three:

St ar t t he RMI registry (r mi r egi st r y )

The rm iregis try i s l i k e t he w hi t e pages of a phone b ook .


It ’s w her e t he c l i ent goes t o get t he pr ox y (t he c l i ent
st ub /hel per ob jec t ).

Step four:

St ar t t he remote serv ice

You hav e t o get t he ser v i c e ob jec t up and r unni ng. Your


ser v i c e i mpl ement at i on c l ass i nst ant i at es an i nst anc e of
t he ser v i c e and r egi st er s i t w i t h t he RMI r egi st r y .
Regi st er i ng i t mak es t he ser v i c e av ai l ab l e f or c l i ent s.

Step one: make a Remote interface

1 . Extend j av a.rmi.Remote

Remot e i s a “mar k er ” i nt er f ac e, w hi c h means i t has no


met hods. It has spec i al meani ng f or RMI, t hough, so y ou
must f ol l ow t hi s r ul e. N ot i c e t hat w e say “ex t ends” her e.
One i nt er f ac e i s al l ow ed t o extend anot her i nt er f ac e.
2. Dec l ar e t hat al l met hods throw RemoteException

The r emot e i nt er f ac e i s t he one t he c l i ent uses as t he t y pe


f or t he ser v i c e. In ot her w or ds, t he c l i ent i nv ok es
met hods on somet hi ng t hat i mpl ement s t he r emot e
i nt er f ac e. That somet hi ng i s t he st ub , of c our se, and si nc e
t he st ub i s doi ng net w or k i ng and I/O, al l k i nds of b ad
t hi ngs c an happen. The c l i ent has t o ac k now l edge t he
r i sk s b y handl i ng or dec l ar i ng t he r emot e ex c ept i ons. If
t he met hods i n an i nt er f ac e dec l ar e ex c ept i ons, any c ode
c al l i ng met hods on a r ef er enc e of t hat t y pe (t he i nt er f ac e
t y pe) must handl e or dec l ar e t he ex c ept i ons.

3. Be sure arguments and return v alues are primitiv es or


Serializable

A r gument s and r et ur n v al ues of a r emot e met hod must b e


ei t her pr i mi t i v e or Ser i al i zab l e. Thi nk ab out i t . A ny
ar gument t o a r emot e met hod has t o b e pac k aged up and
shi pped ac r oss t he net w or k , and t hat ’s done t hr ough
Ser i al i zat i on. The same t hi ng appl i es w i t h r et ur n v al ues.
If y ou use pr i mi t i v es, St r i ngs, and t he major i t y of t y pes
i n t he A PI (i nc l udi ng ar r ay s and c ol l ec t i ons), y ou’l l b e
f i ne. If y ou ar e passi ng ar ound y our ow n t y pes, just b e
sur e t hat y ou mak e y our c l asses i mpl ement Ser i al i zab l e.

N O TE
Check out your favorite Java reference if you need
to refresh your memory on Serializable.

Step two: make a Remote implementation

1 . I mplement the Remote interface

Your ser v i c e has t o i mpl ement t he r emot e i nt er f ac e—t he


one w i t h t he met hods y our c l i ent i s goi ng t o c al l .

2. Extend UnicastRemoteObj ect

In or der t o w or k as a r emot e ser v i c e ob jec t , y our ob jec t


needs some f unc t i onal i t y r el at ed t o “b ei ng r emot e.” The
si mpl est w ay i s t o ex t end U ni c ast Remot eOb jec t (f r om t he
jav a.r mi .ser v er pac k age) and l et t hat c l ass (y our
super c l ass) do t he w or k f or y ou.

3. Write a no-arg constructor that declares


RemoteException

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.

4. Register the serv ice with the RMI registry

N ow t hat y ou’v e got a r emot e ser v i c e, y ou hav e t o mak e i t


av ai l ab l e t o r emot e c l i ent s. You do t hi s b y i nst ant i at i ng
i t and put t i ng i t i nt o t he RMI r egi st r y (w hi c h must b e
r unni ng or t hi s l i ne of c ode f ai l s). W hen y ou r egi st er t he
i mpl ement at i on ob jec t , t he RMI sy st em ac t ual l y put s t he
s tub i n t he r egi st r y , si nc e t hat ’s w hat t he c l i ent r eal l y
needs. Regi st er y our ser v i c e usi ng t he st at i c r eb i nd()
met hod of t he jav a.r mi .N ami ng c l ass.
Step four: start the service

1 . Bring up a terminal and start the rmiregistry .

Be sur e y ou st ar t i t f r om a di r ec t or y t hat has ac c ess t o


y our c l asses. The si mpl est w ay i s t o st ar t i t f r om y our
c las s es di r ec t or y .

Step four: start the service

1 . Bring up another terminal and start y our serv ice

Thi s mi ght b e f r om a mai n() met hod i n y our r emot e


i mpl ement at i on c l ass or f r om a separ at e l aunc her c l ass.
In t hi s si mpl e ex ampl e, w e put t he st ar t er c ode i n t he
i mpl ement at i on c l ass, i n a mai n met hod t hat i nst ant i at es
t he ob jec t and r egi st er s i t w i t h RMI r egi st r y .

there are no Dumb Questions


Q: Why are y ou showing stubs and skeletons in the diagrams for
the RMI code? I thought we got rid of those way back.

A: You’r e r i ght ; f or t he sk el et on, t he RMI r unt i me c an di spat c h t he


c l i ent c al l s di r ec t l y t o t he r emot e ser v i c e usi ng r ef l ec t i on, and
st ub s ar e gener at ed dy nami c al l y usi ng Dy nami c Pr ox y (w hi c h
y ou’l l l ear n mor e ab out a b i t l at er i n t he c hapt er ). The r emot e
ob jec t ’s st ub i s a jav a.l ang.r ef l ec t .Pr ox y i nst anc e (w i t h an
i nv oc at i on handl er ) t hat i s aut omat i c al l y gener at ed t o handl e al l
t he det ai l s of get t i ng t he l oc al met hod c al l s b y t he c l i ent t o t he
r emot e ob jec t . But w e l i k e t o show b ot h t he st ub and sk el et on,
b ec ause c onc ept ual l y i t hel ps y ou t o under st and t hat t her e i s
somet hi ng under t he c ov er s t hat ’s mak i ng t hat c ommuni c at i on
b et w een t he c l i ent st ub and t he r emot e ser v i c e happen.

Complete code for the server side


Let ’s t ak e a l ook at al l t he c ode f or t he ser v er si de:

The Remote interface:

The Remote serv ice (the implementation):


And that’s where the RMI registry comes in.

A nd, y ou’r e r i ght ; t he c l i ent has t o get t he st ub ob jec t (our pr ox y ),


b ec ause t hat ’s t he t hi ng t he c l i ent w i l l c al l met hods on. To do t hat ,
t he c l i ent does a “l ook up,” l i k e goi ng t o t he w hi t e pages of a phone
b ook , and essent i al l y say s, “Her e’s a name, and I’d l i k e t he st ub t hat
goes w i t h t hat name.”

Let ’s t ak e a l ook at t he c ode w e need t o l ook up and r et r i ev e a st ub


ob jec t .

C O D E U P C L O SE

How it works...

1 . Client does a lookup on the RMI registry

Naming.lookup("rmi://127.0.0.1/RemoteHello");

2. RMI registry returns the stub obj ect

(as t he r et ur n v al ue of t he l ook up met hod) and RMI


deser i al i zes t he st ub aut omat i c al l y .

3. Client inv okes a method on the stub, as if the stub I S


the real serv ice

Complete code for the client side


Let ’s t ak e a l ook at al l t he c ode f or t he c l i ent si de:
W AT C H IT !
The things programmers do wrong with RMI are:

1. Forget to start rmiregistry before starting the remote service


(w hen the service is registered using Naming. rebind(), the
rmiregistry must be running!)

2. Forget to make arguments and return types serializable (you


w on’t know until runtime; this is not something the compiler w ill
detect).

Back to our GumballMachine remote proxy


Ok ay , now t hat y ou hav e t he RMI b asi c s dow n, y ou’v e got t he t ool s
y ou need t o i mpl ement t he gumb al l mac hi ne r emot e pr ox y . Let ’s
t ak e a l ook at how t he Gumb al l Mac hi ne f i t s i nt o t hi s f r amew or k :

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.

Getting the GumballMachine ready to be a remote


service
The f i r st st ep i n c onv er t i ng our c ode t o use t he r emot e pr ox y i s t o
enab l e t he Gumb al l Mac hi ne t o ser v i c e r emot e r equest s f r om
c l i ent s. In ot her w or ds, w e’r e goi ng t o mak e i t i nt o a ser v i c e. To do
t hat , w e need t o:

1 . Cr eat e a r emot e i nt er f ac e f or t he Gumb al l Mac hi ne. Thi s


w i l l pr ov i de a set of met hods t hat c an b e c al l ed r emot el y .

2. Mak e sur e al l t he r et ur n t y pes i n t he i nt er f ac e ar e


ser i al i zab l e.

3. Impl ement t he i nt er f ac e i n a c onc r et e c l ass.

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...

A c t ual l y , w e’r e not done w i t h Ser i al i zab l e y et ; w e hav e one


pr ob l em w i t h St at e. A s y ou may r ememb er , eac h St at e ob jec t
mai nt ai ns a r ef er enc e t o a gumb al l mac hi ne so t hat i t c an c al l t he
gumb al l mac hi ne’s met hods and c hange i t s st at e. W e don’t w ant t he
ent i r e gumb al l mac hi ne ser i al i zed and t r ansf er r ed w i t h t he St at e
ob jec t . Ther e i s an easy w ay t o f i x t hi s:

W e’v e al r eady i mpl ement ed our Gumb al l Mac hi ne, b ut w e need t o


mak e sur e i t c an ac t as a ser v i c e and handl e r equest s c omi ng f r om
ov er t he net w or k . To do t hat , w e hav e t o mak e sur e t he
Gumb al l Mac hi ne i s doi ng ev er y t hi ng i t needs t o i mpl ement t he
Gumb al l Mac hi neRemot e i nt er f ac e.

A s y ou’v e al r eady seen i n t he RMI det our , t hi s i s qui t e si mpl e; al l


w e need t o do i s add a c oupl e of t hi ngs...

Registering with the RMI registry...


That c ompl et es t he gumb al l mac hi ne ser v i c e. N ow w e just need t o
f i r e i t up so i t c an r ec ei v e r equest s. Fi r st , w e need t o mak e sur e w e
r egi st er i t w i t h t he RMI r egi st r y so t hat c l i ent s c an l oc at e i t .

W e’r e goi ng t o add a l i t t l e c ode t o t he t est dr i v e t hat w i l l t ak e c ar e


of t hi s f or us:

Let ’s go ahead and get t hi s r unni ng...

Now for the GumballMonitor client...


Rememb er t he Gumb al l Moni t or ? W e w ant ed t o r euse i t w i t hout
hav i ng t o r ew r i t e i t t o w or k ov er a net w or k . W el l , w e’r e pr et t y
muc h goi ng t o do t hat , b ut w e do need t o mak e a f ew c hanges.
Writing the Monitor test drive
N ow w e’v e got al l t he pi ec es w e need. W e just need t o w r i t e some
c ode so t he CEO c an moni t or a b unc h of gumb al l mac hi nes:

C O D E U P C L O SE

Another demo for the CEO of Mighty Gumball...


Ok ay , i t ’s t i me t o put al l t hi s w or k t oget her and gi v e anot her demo.
Fi r st l et ’s mak e sur e a f ew gumb al l mac hi nes ar e r unni ng t he new
c ode:

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 ).

1 . The CEO r uns t he moni t or , w hi c h f i r st gr ab s t he pr ox i es


t o t he r emot e gumb al l mac hi nes and t hen c al l s get St at e()
on eac h one (al ong w i t h get Count () and get Loc at i on()).

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.

3. Gumb al l Mac hi ne r et ur ns t he st at e t o t he sk el et on, w hi c h


ser i al i zes i t and t r ansf er s i t b ac k ov er t he w i r e t o t he
pr ox y . The pr ox y deser i al i zes i t and r et ur ns i t as an
ob jec t t o t he moni t or .
N O TE
We also have a small bit of code to register and
locate stubs using the RMI registry. But no matter
what, if we were writing something to work over the
internet, we’d need some kind of locator service.

The Proxy Pattern defined


W e’v e al r eady put a l ot of pages b ehi nd us i n t hi s c hapt er ; as y ou
c an see, ex pl ai ni ng t he Remot e Pr ox y i s qui t e i nv ol v ed. Despi t e
t hat , y ou’l l see t hat t he def i ni t i on and c l ass di agr am f or t he Pr ox y
Pat t er n i s ac t ual l y f ai r l y st r ai ght f or w ar d. N ot e t hat t he Remot e
Pr ox y i s one i mpl ement at i on of t he gener al Pr ox y Pat t er n; t her e
ar e ac t ual l y qui t e a f ew v ar i at i ons of t he pat t er n, and w e’l l t al k
ab out t hem l at er . For now , l et ’s get t he det ai l s of t he gener al
pat t er n dow n.

Her e’s t he Pr ox y Pat t er n def i ni t i on:

N O TE
The Proxy Pattern provides a surrogate or placeholder for
another object to control access to it.

W el l , w e’v e seen how t he Pr ox y Pat t er n pr ov i des a sur r ogat e or


pl ac ehol der f or anot her ob jec t . W e’v e al so desc r i b ed t he pr ox y as a
“r epr esent at i v e” f or anot her ob jec t .

But w hat ab out a pr ox y c ont r ol l i ng ac c ess? That sounds a l i t t l e


st r ange. N o w or r i es. In t he c ase of t he gumb al l mac hi ne, just t hi nk
of t he pr ox y c ont r ol l i ng ac c ess t o t he r emot e ob jec t . The pr ox y
needed t o c ont r ol ac c ess b ec ause our c l i ent , t he moni t or , di dn’t
k now how t o t al k t o a r emot e ob jec t . So i n some sense t he r emot e
pr ox y c ont r ol l ed ac c ess so t hat i t c oul d handl e t he net w or k det ai l s
f or us. A s w e just di sc ussed, t her e ar e many v ar i at i ons of t he Pr ox y
Pat t er n, and t he v ar i at i ons t y pi c al l y r ev ol v e ar ound t he w ay t he
pr ox y “c ont r ol s ac c ess.” W e’r e goi ng t o t al k mor e ab out t hi s l at er ,
b ut f or now her e ar e a f ew w ay s pr ox i es c ont r ol ac c ess:

Us e th e Pro xy Pa tte rn to cre a te a re p re s e nta tiv e


o b je ct th a t co ntro ls a cce s s to a no th e r o b je ct, w h ich
m a y b e re m o te , e xp e ns iv e to cre a te , o r in ne e d o f
s e curing .

A s w e k now , a r emot e pr ox y c ont r ol s ac c ess t o a r emot e


ob jec t .

A v i r t ual pr ox y c ont r ol s ac c ess t o a r esour c e t hat i s


ex pensi v e t o c r eat e.

A pr ot ec t i on pr ox y c ont r ol s ac c ess t o a r esour c e b ased on


ac c ess r i ght s.

N ow t hat y ou’v e got t he gi st of t he gener al pat t er n, c hec k out t he


c l ass di agr am...

Let ’s st ep t hr ough t he di agr am...

Fi r st w e hav e a Sub jec t , w hi c h pr ov i des an i nt er f ac e f or t he


Real Sub jec t and t he Pr ox y . Bec ause i t i mpl ement s t he same
i nt er f ac e as t he Real Sub jec t , t he Pr ox y c an b e sub st i t ut ed f or t he
Real Sub jec t any w her e i t oc c ur s.

The Real Sub jec t i s t he ob jec t t hat does t he r eal w or k . It ’s t he ob jec t


t hat t he Pr ox y r epr esent s and c ont r ol s ac c ess t o.

The Pr ox y hol ds a r ef er enc e t o t he Real Sub jec t . In some c ases, t he


Pr ox y may b e r esponsi b l e f or c r eat i ng and dest r oy i ng t he
Real Sub jec t . Cl i ent s i nt er ac t w i t h t he Real Sub jec t t hr ough t he
Pr ox y . Bec ause t he Pr ox y and Real Sub jec t i mpl ement t he same
i nt er f ac e (Sub jec t ), t he Pr ox y c an b e sub st i t ut ed any w her e t he
Sub jec t c an b e used. The Pr ox y al so c ont r ol s ac c ess t o t he
Real Sub jec t ; t hi s c ont r ol may b e needed i f t he Sub jec t i s r unni ng
on a r emot e mac hi ne, i f t he Sub jec t i s ex pensi v e t o c r eat e i n some
w ay , or i f ac c ess t o t he sub jec t needs t o b e pr ot ec t ed i n some w ay .
N ow t hat y ou under st and t he gener al pat t er n, l et ’s l ook at some
ot her w ay s of usi ng pr ox y b ey ond t he Remot e Pr ox y ...

Get ready for the Virtual Proxy


Ok ay , so f ar y ou’v e seen t he def i ni t i on of t he Pr ox y Pat t er n and
y ou’v e t ak en a l ook at one spec i f i c ex ampl e: t he Rem ote Proxy . N ow
w e’r e goi ng t o t ak e a l ook at a di f f er ent t y pe of pr ox y , t he Virtual
Proxy . A s y ou’l l di sc ov er , t he Pr ox y Pat t er n c an mani f est i t sel f i n
many f or ms, y et al l t he f or ms f ol l ow r oughl y t he gener al pr ox y
desi gn. W hy so many f or ms? Bec ause t he Pr ox y Pat t er n c an b e
appl i ed t o a l ot of di f f er ent use c ases. Let ’s c hec k out t he V i r t ual
Pr ox y and c ompar e i t t o t he Remot e Pr ox y :

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 .

Displaying Album covers


Let ’s say y ou w ant t o w r i t e an appl i c at i on t hat di spl ay s y our
f av or i t e al b um c ov er s. You mi ght c r eat e a menu of t he al b um t i t l es
and t hen r et r i ev e t he i mages f r om an onl i ne ser v i c e l i k e
A mazon.c om (http://Amazon.com) . If y ou’r e usi ng Sw i ng, y ou mi ght c r eat e
an Ic on and ask i t t o l oad t he i mage f r om t he net w or k . The onl y
pr ob l em i s, dependi ng on t he net w or k l oad and t he b andw i dt h of
y our c onnec t i on, r et r i ev i ng an al b um c ov er mi ght t ak e a l i t t l e
t i me, so y our appl i c at i on shoul d di spl ay somet hi ng w hi l e y ou’r e
w ai t i ng f or t he i mage t o l oad. W e al so don’t w ant t o hang up t he
ent i r e appl i c at i on w hi l e i t ’s w ai t i ng on t he i mage. Onc e t he i mage
i s l oaded, t he message shoul d go aw ay and y ou shoul d see t he i mage.

A n easy w ay t o ac hi ev e t hi s i s t hr ough a v i r t ual pr ox y . The v i r t ual


pr ox y c an st and i n pl ac e of t he i c on, manage t he b ac k gr ound
l oadi ng, and b ef or e t he i mage i s f ul l y r et r i ev ed f r om t he net w or k ,
di spl ay “Loadi ng al b um c ov er , pl ease w ai t ...”. Onc e t he i mage i s
l oaded, t he pr ox y del egat es t he di spl ay t o t he Ic on.

Designing the Album Cover Virtual Proxy


Bef or e w r i t i ng t he c ode f or t he A l b um Cov er V i ew er , l et ’s l ook at
t he c l ass di agr am. You’l l see t hi s l ook s just l i k e our Remot e Pr ox y
c l ass di agr am, b ut her e t he pr ox y i s used t o hi de an ob jec t t hat i s
ex pensi v e t o c r eat e (b ec ause w e need t o r et r i ev e t he dat a f or t he
Ic on ov er t he net w or k ) as opposed t o an ob jec t t hat ac t ual l y l i v es
somew her e el se on t he net w or k .

How ImageProxy is going to work:

1 . I mageProxy first creates an I mageI con and starts


loading it from a network URL.

2. While the by tes of the image are being retriev ed,


I mageProxy display s “Loading album cov er, please
wait...”.

3. When the image is fully loaded, I mageProxy delegates


all method calls to the image icon, including
paintI con(), getI conWidth(), and getI conHeight().

4. I f the user requests a new image, we’ll create a new


proxy and start the process ov er.

Writing the Image Proxy

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?

Testing the Album Cover Viewer

Ok ay , i t ’s t i me t o t est out t hi s f anc y new v i r t ual pr ox y . Behi nd t he


sc enes w e’v e b een b ak i ng up a new ImagePr ox y Test Dr i v e t hat set s
up t he w i ndow , c r eat es a f r ame, i nst al l s t he menus, and c r eat es our
pr ox y . W e don’t go t hr ough al l t hat c ode i n gor y det ai l her e, b ut
y ou c an al w ay s gr ab t he sour c e c ode and hav e a l ook , or c hec k i t out
at t he end of t he c hapt er w her e w e l i st al l t he sour c e c ode f or t he
V i r t ual Pr ox y .

Her e’s a par t i al v i ew of t he t est dr i v e c ode:

N ow l et ’s r un t he t est dr i v e:
Things to try...

1 . U se t he menu t o l oad di f f er ent al b um c ov er s; w at c h t he


pr ox y di spl ay “l oadi ng” unt i l t he i mage has ar r i v ed.

2. Resi ze t he w i ndow as t he “l oadi ng” message i s di spl ay ed.


N ot i c e t hat t he pr ox y i s handl i ng t he l oadi ng w i t hout
hangi ng up t he Sw i ng w i ndow .

3. A dd y our ow n f av or i t e al b ums t o ImagePr ox y Test Dr i v e.

What did we do?

1 . W e c r eat ed an ImagePr ox y c l ass f or t he di spl ay . The


pai nt Ic on() met hod i s c al l ed and ImagePr ox y f i r es of f a
t hr ead t o r et r i ev e t he i mage and c r eat e t he ImageIc on.

2. A t some poi nt t he i mage i s r et ur ned and t he ImageIc on


f ul l y i nst ant i at ed.

3. A f t er t he ImageIc on i s c r eat ed, t he nex t t i me pai nt Ic on()


i s c al l ed, t he pr ox y del egat es t o t he ImageIc on.

there are no Dumb Questions


Q: The Remote Proxy and Virtual Proxy seem so different to me;
are they really ONE pattern?

A: You’l l f i nd a l ot of v ar i ant s of t he Pr ox y Pat t er n i n t he r eal


w or l d; w hat t hey al l hav e i n c ommon i s t hat t hey i nt er c ept a
met hod i nv oc at i on t hat t he c l i ent i s mak i ng on t he sub jec t . Thi s
l ev el of i ndi r ec t i on al l ow s us t o do many t hi ngs, i nc l udi ng
di spat c hi ng r equest s t o a r emot e sub jec t , pr ov i di ng a
r epr esent at i v e f or an ex pensi v e ob jec t as i t i s c r eat ed, or , as y ou’l l
see, pr ov i di ng some l ev el of pr ot ec t i on t hat c an det er mi ne w hi c h
c l i ent s shoul d b e c al l i ng w hi c h met hods. That ’s just t he b egi nni ng;
t he gener al Pr ox y Pat t er n c an b e appl i ed i n many di f f er ent w ay s,
and w e’l l c ov er some of t he ot her w ay s at t he end of t he c hapt er .

Q: I mageProxy seems j ust like a Decorator to me. I mean, we


are basically wrapping one obj ect with another and then
delegating the calls to the I mageI con. What am I missing?

A: Somet i mes Pr ox y and Dec or at or l ook v er y si mi l ar , b ut t hei r


pur poses ar e di f f er ent : a dec or at or adds b ehav i or t o a c l ass, w hi l e a
pr ox y c ont r ol s ac c ess t o i t . You mi ght ask , “Isn’t t he l oadi ng message
addi ng b ehav i or ?” In some w ay s i t i s; how ev er , mor e i mpor t ant l y ,
t he ImagePr ox y i s c ont r ol l i ng ac c ess t o an ImageIc on. How does i t
c ont r ol ac c ess? W el l , t hi nk ab out i t t hi s w ay : t he pr ox y i s
dec oupl i ng t he c l i ent f r om t he ImageIc on. If t hey w er e c oupl ed t he
c l i ent w oul d hav e t o w ai t unt i l eac h i mage i s r et r i ev ed b ef or e i t
c oul d pai nt i t s ent i r e i nt er f ac e. The pr ox y c ont r ol s ac c ess t o t he
ImageIc on so t hat b ef or e i t i s f ul l y c r eat ed, t he pr ox y pr ov i des
anot her onsc r een r epr esent at i on. Onc e t he ImageIc on i s c r eat ed,
t he pr ox y al l ow s ac c ess.

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.

Q: I noticed in the I mageProxy example, y ou alway s create a


new I mageI con to get the image, ev en if the image has already
been retriev ed. Could y ou implement something similar to the
I mageProxy that caches past retriev als?

A: You ar e t al k i ng ab out a spec i al i zed f or m of a V i r t ual Pr ox y


c al l ed a Cac hi ng Pr ox y . A c ac hi ng pr ox y mai nt ai ns a c ac he of
pr ev i ousl y c r eat ed ob jec t s and w hen a r equest i s made i t r et ur ns a
c ac hed ob jec t , i f possi b l e.

W e’r e goi ng t o l ook at t hi s and at sev er al ot her v ar i ant s of t he


Pr ox y Pat t er n at t he end of t he c hapt er .

Q: I see how Decorator and Proxy relate, but what about


Adapter? An adapter seems v ery similar as well.

A: Bot h Pr ox y and A dapt er si t i n f r ont of ot her ob jec t s and f or w ar d


r equest s t o t hem. Rememb er t hat A dapt er c hanges t he i nt er f ac e of
t he ob jec t s i t adapt s, w hi l e Pr ox y i mpl ement s t he same i nt er f ac e.

Ther e i s one addi t i onal si mi l ar i t y t hat r el at es t o t he Pr ot ec t i on


Pr ox y . A Pr ot ec t i on Pr ox y may al l ow or di sal l ow a c l i ent ac c ess t o
par t i c ul ar met hods i n an ob jec t b ased on t he r ol e of t he c l i ent . In
t hi s w ay a Pr ot ec t i on Pr ox y may onl y pr ov i de a par t i al i nt er f ac e
t o a c l i ent , w hi c h i s qui t e si mi l ar t o some A dapt er s. W e ar e goi ng t o
t ak e a l ook at Pr ot ec t i on Pr ox y i n a f ew pages.

Toni ght ’s t al k : Proxy and Decorator get intentional.


Proxy: Decorator:

Hello, Decorator. I presume you’re here


because people sometimes get us
confused?

Well, I think the reason people get us


confused is that you go around pretending
to be an entirely different pattern, when in
fact, you’re just Decorator in disguise. I
really don’t think you should be copying
all my ideas.

Me copying your ideas? Please. I control


access to objects. You just decorate them.
My job is so much more important than
yours it’s just not even funny.

“Just” decorate? You think decorating is


some frivolous, unimportant pattern? Let
me tell you buddy, I add behavior. That’s
the most important thing about objects—
what they do!

Fine, so maybe you’re not entirely


frivolous...but I still don’t get why you
think I’m copying all your ideas. I’m all
about representing my subjects, not
decorating them.

You can call it “representation” but if it


looks like a duck and walks like a duck...
I mean, just look at your Virtual Proxy;
it’s just another way of adding behavior to
do something while some big expensive
object is loading, and your Remote Proxy
is a way of talking to remote objects so
your clients don’t have to bother with that
themselves. It’s all about behavior, just
like I said.

I don’t think you get it, Decorator. I stand


in for my Subjects; I don’t just add
behavior. Clients use me as a surrogate of
a Real Subject, because I can protect them
from unwanted access, or keep their GUIs
from hanging up while they’re waiting for
big objects to load, or hide the fact that
their Subjects are running on remote
machines. I’d say that’s a very different
intent from yours!

Call it what you want. I implement the


same interface as the objects I wrap; so do
you.

Okay, let’s review that statement. You


wrap an object. While sometimes we
informally say a proxy wraps its Subject,
that’s not really an accurate term.

Oh yeah? Why not?

Think about a remote proxy...what object


am I wrapping? The object I’m
representing and controlling access to
lives on another machine! Let’s see you do
that.

Okay, but we all know remote proxies are


kinda weird. Got a second example? I
doubt it.

Sure, okay, take a virtual proxy...think


about the album viewer example. When
the client first uses me as a proxy the
subject doesn’t even exist! So what am I
wrapping there?

Uh huh, and the next thing you’ll be


saying is that you actually get to create
objects.

I never knew decorators were so dumb! Of


course I sometimes create objects. How do
you think a virtual proxy gets its subject?!
Okay, you just pointed out a big difference
between us: we both know decorators only
add window dressing; they never get to
instantiate anything.

Oh yeah? Instantiate this!

Hey, after this conversation I’m convinced


you’re just a dumb proxy!

Dumb proxy? I’d like to see you recursively


wrap an object with 10 decorators and
keep your head straight at the same time.

Very seldom will you ever see a proxy get


into wrapping a subject multiple times; in
fact, if you’re wrapping something 10
times, you better go back reexamine your
design.

Just like a proxy, acting all real when in


fact you just stand in for the objects doing
the real work. You know, I actually feel
sorry for you.

Using the Java API’s Proxy to create a protection proxy

Jav a’s got i t s ow n pr ox y suppor t r i ght i n t he jav a.l ang.r ef l ec t


pac k age. W i t h t hi s pac k age, Jav a l et s y ou c r eat e a pr ox y c l ass on
th e fly t hat i mpl ement s one or mor e i nt er f ac es and f or w ar ds met hod
i nv oc at i ons t o a c l ass t hat y ou spec i f y . Bec ause t he ac t ual pr ox y
c l ass i s c r eat ed at r unt i me, w e r ef er t o t hi s Jav a t ec hnol ogy as a
dy nam ic proxy .
W e’r e goi ng t o use Jav a’s dy nami c pr ox y t o c r eat e our nex t pr ox y
i mpl ement at i on (a pr ot ec t i on pr ox y ), b ut b ef or e w e do t hat , l et ’s
qui c k l y l ook at a c l ass di agr am t hat show s how dy nami c pr ox i es ar e
put t oget her . Li k e most t hi ngs i n t he r eal w or l d, i t di f f er s sl i ght l y
f r om t he c l assi c def i ni t i on of t he pat t er n:

Bec ause Jav a c r eat es t he Pr ox y c l ass for y ou, y ou need a w ay t o t el l


t he Pr ox y c l ass w hat t o do. You c an’t put t hat c ode i nt o t he Pr ox y
c l ass l i k e w e di d b ef or e, b ec ause y ou’r e not i mpl ement i ng one
di r ec t l y . So, i f y ou c an’t put t hi s c ode i n t he Pr ox y c l ass, w her e do
y ou put i t ? In an Inv oc at i onHandl er . The job of t he
Inv oc at i onHandl er i s t o r espond t o any met hod c al l s on t he pr ox y .
Thi nk of t he Inv oc at i onHandl er as t he ob jec t t he Pr ox y ask s t o do
al l t he r eal w or k af t er i t has r ec ei v ed t he met hod c al l s.

Ok ay , l et ’s st ep t hr ough how t o use t he dy nami c pr ox y ...

Geeky Matchmaking in Objectville


Ev er y t ow n needs a mat c hmak i ng ser v i c e, r i ght ? You’v e r i sen t o t he
t ask and i mpl ement ed a dat i ng ser v i c e f or Ob jec t v i l l e. You’v e al so
t r i ed t o b e i nnov at i v e b y i nc l udi ng a “Geek r at i ng” f eat ur e w her e
par t i c i pant s c an r at e eac h ot her ’s geek i ness (a good t hi ng)—y ou
f i gur e t hi s k eeps y our c ust omer s engaged and l ook i ng t hr ough
possi b l e mat c hes; i t al so mak es t hi ngs a l ot mor e f un.

Your ser v i c e r ev ol v es ar ound a Per son i nt er f ac e t hat al l ow s y ou t o


set and get i nf or mat i on ab out a per son:

N ow l et ’s c hec k out t he i mpl ement at i on...

The Person implementation


W hi l e w e suspec t ot her f ac t or s may b e k eepi ng El r oy f r om get t i ng
dat es, he’s r i ght : y ou shoul dn’t b e ab l e t o v ot e f or y our sel f or t o
c hange anot her c ust omer ’s dat a. The w ay Per son i s def i ned, any
c l i ent c an c al l any of t he met hods.

Thi s i s a per f ec t ex ampl e of w her e w e mi ght b e ab l e t o use a


Pr ot ec t i on Pr ox y . W hat ’s a Pr ot ec t i on Pr ox y ? It ’s a pr ox y t hat
c ont r ol s ac c ess t o an ob jec t b ased on ac c ess r i ght s. For i nst anc e, i f
w e had an empl oy ee ob jec t , a Pr ot ec t i on Pr ox y mi ght al l ow t he
empl oy ee t o c al l c er t ai n met hods on t he ob jec t , a manager t o c al l
addi t i onal met hods (l i k e set Sal ar y ()), and a human r esour c es
empl oy ee t o c al l any met hod on t he ob jec t .

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.

Five-minute drama: protecting subjects


The i nt er net b ub b l e seems a di st ant memor y ; t hose w er e t he day s
w hen al l y ou needed t o do t o f i nd a b et t er , hi gher -pay i ng job w as t o
w al k ac r oss t he st r eet . Ev en agent s f or sof t w ar e dev el oper s w er e i n
v ogue...
Big Picture: creating a Dynamic Proxy for the Person
W e hav e a c oupl e of pr ob l ems t o f i x : c ust omer s shoul dn’t b e
c hangi ng t hei r ow n Geek r at i ng and c ust omer s shoul dn’t b e ab l e t o
c hange ot her c ust omer s’ per sonal i nf or mat i on. To f i x t hese
pr ob l ems w e’r e goi ng t o c r eat e t w o pr ox i es: one f or ac c essi ng y our
ow n Per son ob jec t and one f or ac c essi ng anot her c ust omer ’s Per son
ob jec t . That w ay , t he pr ox i es c an c ont r ol w hat r equest s c an b e made
i n eac h c i r c umst anc e.

To c r eat e t hese pr ox i es w e’r e goi ng t o use t he Jav a A PI’s dy nami c


pr ox y t hat y ou saw a f ew pages b ac k . Jav a w i l l c r eat e t w o pr ox i es
f or us; al l w e need t o do i s suppl y t he handl er s t hat k now w hat t o do
w hen a met hod i s i nv ok ed on t he pr ox y .

Step one:

Cr eat e t w o I nv ocationHandlers.

Inv oc at i onHandl er s i mpl ement t he b ehav i or of t he


pr ox y . A s y ou’l l see, Jav a w i l l t ak e c ar e of c r eat i ng t he
ac t ual pr ox y c l ass and ob jec t ; w e just need t o suppl y a
handl er t hat k now s w hat t o do w hen a met hod i s c al l ed on
i t.

Step two:

W r i t e t he c ode t hat c r eat es t he dy nami c pr ox i es.

W e need t o w r i t e a l i t t l e b i t of c ode t o gener at e t he pr ox y


c l ass and i nst ant i at e i t . W e’l l st ep t hr ough t hi s c ode i n
just a b i t .

Step three:

W r ap any Per son ob jec t w i t h t he appr opr i at e pr ox y .

W hen w e need t o use a Per son ob jec t , ei t her i t ’s t he ob jec t


of t he c ust omer hi msel f (i n t hat c ase, w e’l l c al l hi m t he
“ow ner ”), or i t ’s anot her user of t he ser v i c e t hat t he
c ust omer i s c hec k i ng out (i n t hat c ase w e’l l c al l hi m “non-
ow ner ”).

In ei t her c ase, w e c r eat e t he appr opr i at e pr ox y f or t he


Per son.
Step one: creating Invocation Handlers
W e k now w e need t o w r i t e t w o i nv oc at i on handl er s, one f or t he
ow ner and one f or t he non-ow ner . But w hat ar e i nv oc at i on
handl er s? Her e’s t he w ay t o t hi nk ab out t hem: w hen a met hod c al l
i s made on t he pr ox y , t he pr ox y f or w ar ds t hat c al l t o y our
i nv oc at i on handl er , b ut not b y c al l i ng t he i nv oc at i on handl er ’s
c or r espondi ng met hod. So, w hat does i t c al l ? Hav e a l ook at t he
Inv oc at i onHandl er i nt er f ac e:

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:

Creating Invocation Handlers, continued...


W hen i nv ok e() i s c al l ed b y t he pr ox y , how do y ou k now w hat t o do
w i t h t he c al l ? Ty pi c al l y , y ou’l l ex ami ne t he met hod t hat w as c al l ed
on t he pr ox y and mak e dec i si ons b ased on t he met hod’s name and
possi b l y i t s ar gument s. Let ’s i mpl ement Ow ner Inv oc at i onHandl er
t o 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:

Step two: creating the Proxy class and instantiating the


Proxy object
N ow , al l w e hav e l ef t i s t o dy nami c al l y c r eat e t he Pr ox y c l ass and
i nst ant i at e t he pr ox y ob jec t . Let ’s st ar t b y w r i t i ng a met hod t hat
t ak es a Per son ob jec t and k now s how t o c r eat e an ow ner pr ox y f or
i t . That i s, w e’r e goi ng t o c r eat e t he k i nd of pr ox y t hat f or w ar ds i t s
met hod c al l s t o Ow ner Inv oc at i onHandl er . Her e’s t he c ode:
SH AR PEN YO U R PEN C IL
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
NonOwnerInvocationHandler:

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?

Testing the matchmaking service


Let ’s gi v e t he mat c hmak i ng ser v i c e a t est r un and see how i t
c ont r ol s ac c ess t o t he set t er met hods b ased on t he pr ox y t hat i s
used.

Running the code...

there are no Dumb Questions


Q: So what exactly is the “dy namic” aspect of dy namic proxies?
I s it that I ’m instantiating the proxy and setting it to a handler
at runtime?

A: N o, t he pr ox y i s dy nami c b ec ause i t s c l ass i s c r eat ed at r unt i me.


Thi nk ab out i t : b ef or e y our c ode r uns t her e i s no pr ox y c l ass; i t i s
c r eat ed on demand f r om t he set of i nt er f ac es y ou pass i t .

Q: My I nv ocationHandler seems like a v ery strange proxy ; it


doesn’t implement any of the methods of the class it’s proxy ing.

A: That ’s b ec ause t he Inv oc at i onHandl er i sn’t a pr ox y —i t ’s a c l ass


t hat t he pr ox y di spat c hes t o f or handl i ng met hod c al l s. The pr ox y
i t sel f i s c r eat ed dy nami c al l y at r unt i me b y t he st at i c
Pr ox y .new Pr ox y Inst anc e() met hod.

Q: I s there any way to tell if a class is a Proxy class?

A: Yes. The Pr ox y c l ass has a st at i c met hod c al l ed i sPr ox y Cl ass().


Cal l i ng t hi s met hod w i t h a c l ass w i l l r et ur n t r ue i f t he c l ass i s a
dy nami c pr ox y c l ass. Ot her t han t hat , t he pr ox y c l ass w i l l ac t l i k e
any ot her c l ass t hat i mpl ement s a par t i c ul ar set of i nt er f ac es.

Q: Are there any restrictions on the ty pes of interfaces I can


pass into newProxy I nstance()?

A: Yes, t her e ar e a f ew . Fi r st , i t i s w or t h poi nt i ng out t hat w e


al w ay s pass new Pr ox y Inst anc e() an ar r ay of i nt er f ac es—onl y
i nt er f ac es ar e al l ow ed, no c l asses. The major r est r i c t i ons ar e t hat
al l non-pub l i c i nt er f ac es need t o b e f r om t he same pac k age. You
al so c an’t hav e i nt er f ac es w i t h c l ashi ng met hod names (t hat i s, t w o
i nt er f ac es w i t h a met hod w i t h t he same si gnat ur e). Ther e ar e a f ew
ot her mi nor nuanc es as w el l , so at some poi nt y ou shoul d t ak e a l ook
at t he f i ne pr i nt on dy nami c pr ox i es i n t he jav adoc .

W H O D O ES W H AT ?
Match each pattern with its description:

Pattern Description

Decorator Wraps another object and provides a different interface to it.

Facade Wraps another object and provides additional behavior for it.

Proxy Wraps another object to control access to it.

Adapter Wraps a bunch of objects to simplify their interface.

The Proxy Zoo

W el c ome t o t he Ob jec t v i l l e Zoo!

You now k now ab out t he r emot e, v i r t ual , and pr ot ec t i on pr ox i es,


b ut out i n t he w i l d y ou’r e goi ng t o see l ot s of mut at i ons of t hi s
pat t er n. Ov er her e i n t he Pr ox y c or ner of t he zoo w e’v e got a ni c e
c ol l ec t i on of w i l d pr ox y pat t er ns t hat w e’v e c apt ur ed f or y our
st udy .

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

5. Gr oup of f i r st al b um c ov er di spl ay ed (t w o w or ds).

7 . Commonl y used pr ox y f or w eb ser v i c es (t w o w or ds).

8. In RMI, t he ob jec t t hat t ak es t he net w or k r equest s on t he ser v i c e


si de.

1 1 . Pr ox y t hat pr ot ec t s met hod c al l s f r om unaut hor i zed c al l er s.

1 3. Gr oup t hat di d t he al b um MCMXC a.D.

1 4. A ________ pr ox y c l ass i s c r eat ed at r unt i me.

1 5. Pl ac e t o l ear n ab out t he many pr ox y v ar i ant s.

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.

1 8. W e t ook one of t hese t o l ear n RMI.

1 9. W hy El r oy c oul dn’t get dat es.

DOWN

1 . Ob jec t v i l l e Mat c hmak i ng i s f or ________.

2. Jav a’s dy nami c pr ox y f or w ar ds al l r equest s t o t hi s (t w o w or ds).

3. Thi s ut i l i t y ac t s as a l ook up ser v i c e f or RMI.

4. Pr ox y t hat st ands i n f or ex pensi v e ob jec t s.

6. Remot e ______ w as used t o i mpl ement t he gumb al l mac hi ne


moni t or (t w o w or ds).

9. Sof t w ar e dev el oper agent w as b ei ng t hi s k i nd of pr ox y .

1 0. Our f i r st mi st ak e: t he gumb al l mac hi ne r epor t i ng w as not


_____.

1 2. Si mi l ar t o pr ox y , b ut w i t h a di f f er ent pur pose.

Tools for your Design Toolbox


Your desi gn t ool b ox i s al most f ul l ; y ou’r e pr epar ed f or al most any
desi gn pr ob l em t hat c omes y our w ay .
B U L L ET PO IN T S

T he Proxy Pattern provides a representative for another object in


order to control the client’s access to it. T here are a number of
ways it can manage that access.

A Remote Proxy manages interaction between a client and a


remote object.

A Virtual Proxy controls access to an object that is expensive to


instantiate.

A Protection Proxy controls access to the methods of an object


based on the caller.

Many other variants of the Proxy Pattern exist including caching


proxies, synchronization proxies, firewall proxies, copy-on-write
proxies, and so on.

Proxy is structurally similar to Decorator, but the two patterns


differ in their purpose.

T he Decorator Pattern adds behavior to an object, while Proxy


controls access.

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.

Like any wrapper, proxies will increase the number of classes


and objects in your designs.

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.

Here’s our solution:

import java.lang.reflect.*;

public class NonOwnerInvocationHandler implements


InvocationHandler {
Person person;

public NonOwnerInvocationHandler(Person person) {


this.person = person;
}

public Object invoke(Object proxy, Method method,


Object[] args)
throws IllegalAccessException {

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?

Use the State Pattern: implement two states, ImageLoaded and


ImageNotLoaded. T hen put the code from the if statements into their
respective states. Start in the ImageNotLoaded state and then transition to
the ImageLoaded state once the ImageIcon had been retrieved.

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:

Person getNonOwnerProxy(Person person) {

return (Person) Proxy.newProxyInstance(


person.getClass().getClassLoader(),
person.getClass().getInterfaces(),
new NonOwnerInvocationHandler(person));
}

Design Patterns Crossword Solution

W H O D O ES W H AT SO L U T IO N ?
Match each pattern with its description:

The code for the Album Cover Viewer

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();
}

public ImageProxyTestDrive() throws Exception{


albums.put("Buddha
Bar","http://images.amazon.com/images/P/B00009XBYK.01.LZZZZZZZ.jpg");

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 initialURL = new URL((String)albums.get("Selected


Ambient Works, Vol. 2"));
menuBar = new JMenuBar();
menu = new JMenu("Favorite Albums");
menuBar.add(menu);
frame.setJMenuBar(menuBar);

for(Enumeration e = albums.keys(); e.hasMoreElements();) {


String name = (String)e.nextElement();
JMenuItem menuItem = new JMenuItem(name);
menu.add(menuItem);
menuItem.addActionListener(event -> {
imageComponent.setIcon(
new
ImageProxy(getAlbumUrl(event.getActionCommand())));
frame.repaint();
});
}

// set up frame and menus

Icon icon = new ImageProxy(initialURL);


imageComponent = new ImageComponent(icon);
frame.getContentPane().add(imageComponent);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
frame.setVisible(true);

}
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.*;

class ImageProxy implements Icon {


volatile ImageIcon imageIcon;
final URL imageURL;
Thread retrievalThread;
boolean retrieving = false;

public ImageProxy(URL url) { imageURL = url; }

public int getIconWidth() {


if (imageIcon != null) {
return imageIcon.getIconWidth();
} else {
return 800;
}
}

public int getIconHeight() {


if (imageIcon != null) {
return imageIcon.getIconHeight();
} else {
return 600;
}
}

synchronized void setImageIcon(ImageIcon imageIcon) {


this.imageIcon = imageIcon;
}

public void paintIcon(final Component c, Graphics g, int x, int


y) {
if (imageIcon != null) {
imageIcon.paintIcon(c, g, x, y);
} else {
g.drawString("Loading album cover, please wait...",
x+300, y+190);
if (!retrieving) {
retrieving = true;
retrievalThread = new Thread(new Runnable() {
public void run() {
try {
setImageIcon(new ImageIcon(imageURL,
"Album Cover"));
c.repaint();
} catch (Exception e) {
e.printStackTrace();
}
}
});
retrievalThread.start();
}
}
}
}

package headfirst.designpatterns.proxy.virtualproxy;
import java.awt.*;
import javax.swing.*;

class ImageComponent extends JComponent {


private Icon icon;

public ImageComponent(Icon icon) {


this.icon = icon;
}

public void setIcon(Icon icon) {


this.icon = icon;
}

public void paintComponent(Graphics g) {


super.paintComponent(g);
int w = icon.getIconWidth();
int h = icon.getIconHeight();
int x = (800 - w)/2;
int y = (600 - h)/2;
icon.paintIcon(this, g, x, y);
}
}
Chapter 12. Patterns of Patterns:
Compound Patterns

Who would hav e ev er guessed that Patterns could work


together? You’v e al r eady w i t nessed t he ac r i moni ous Fi r esi de
Chat s (and y ou hav en’t ev en seen t he Pat t er n Deat h Mat c h pages
t hat t he edi t or f or c ed us t o r emov e f r om t he b ook ), so w ho w oul d
hav e t hought pat t er ns c an ac t ual l y get al ong w el l t oget her ? W el l ,
b el i ev e i t or not , some of t he most pow er f ul OO desi gns use sev er al
pat t er ns t oget her . Get r eady t o t ak e y our pat t er n sk i l l s t o t he nex t
l ev el ; i t ’s t i me f or c ompound pat t er ns.

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!

You’l l f i nd a l ot of c ompound pat t er ns i n use i n t he r eal w or l d. N ow


t hat y ou’v e got pat t er ns i n y our b r ai n, y ou’l l see t hat t hey ar e
r eal l y just pat t er ns w or k i ng t oget her , and t hat mak es t hem easi er
t o under st and.

W e’r e goi ng t o st ar t t hi s c hapt er b y r ev i si t i ng our f r i endl y duc k s


i n t he Si mU Duc k duc k si mul at or . It ’s onl y f i t t i ng t hat t he duc k s
shoul d b e her e w hen w e c omb i ne pat t er ns; af t er al l , t hey ’v e b een
w i t h us t hr oughout t he ent i r e b ook and t hey ’v e b een good spor t s
ab out t ak i ng par t i n l ot s of pat t er ns. The duc k s ar e goi ng t o hel p
y ou under st and how pat t er ns c an w or k t oget her i n t he same
sol ut i on. But just b ec ause w e’v e c omb i ned some pat t er ns doesn’t
mean w e hav e a sol ut i on t hat qual i f i es as a c ompound pat t er n. For
t hat , i t has t o b e a gener al -pur pose sol ut i on t hat c an b e appl i ed t o
many pr ob l ems. So, i n t he sec ond hal f of t he c hapt er w e’l l v i si t a
real c ompound pat t er n: t he Model -V i ew -Cont r ol l er , ot her w i se
k now n as MV C. If y ou hav en’t hear d of MV C, y ou w i l l , and y ou’l l
f i nd MV C i s one of t he most pow er f ul c ompound pat t er ns i n y our
desi gn t ool b ox .

Pa tte rns a re o fte n us e d to g e th e r a nd co m b ine d


w ith in th e s a m e d e s ig n s o lutio n.

A co m p o und p a tte rn co m b ine s tw o o r m o re p a tte rns


into a s o lutio n th a t s o lv e s a re curring o r g e ne ra l
p ro b le m .

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.

W e’r e goi ng t o r eb ui l d our duc k si mul at or f r om sc r at c h and gi v e i t


some i nt er est i ng c apab i l i t i es b y usi ng a b unc h of pat t er ns. Ok ay ,
l et ’s get st ar t ed...
1 . F irst, we’ll create a Quackable interface.

Li k e w e sai d, w e’r e st ar t i ng f r om sc r at c h. Thi s t i me


ar ound, t he Duc k s ar e goi ng t o i mpl ement a Quac k ab l e
i nt er f ac e. That w ay w e’l l k now w hat t hi ngs i n t he
si mul at or c an quac k ()—l i k e Mal l ar d Duc k s, Redhead
Duc k s, Duc k Cal l s, and w e mi ght ev en see t he Rub b er
Duc k sneak b ac k i n.

2. Now, some Ducks that implement Quackable

W hat good i s an i nt er f ac e w i t hout some c l asses t o


i mpl ement i t ? Ti me t o c r eat e some c onc r et e duc k s (b ut
not t he “l aw n ar t ” k i nd, i f y ou k now w hat w e mean).

This wouldn’t be much fun if we didn’t add other kinds


of Ducks too.

Rememb er l ast t i me? W e had duc k c al l s (t hose t hi ngs


hunt er s use—t hey ar e def i ni t el y quac k ab l e) and r ub b er
duc k s.

3. Okay , we’v e got our ducks; now all we need is a


simulator.

Let ’s c ook up a si mul at or t hat c r eat es a f ew duc k s and


mak es sur e t hei r quac k er s ar e w or k i ng...

It l ook s l i k e ev er y t hi ng i s w or k i ng; so f ar , so good.

4. When ducks are around, geese can’t be far.

W her e t her e i s one w at er f ow l , t her e ar e pr ob ab l y t w o.


Her e’s a Goose c l ass t hat has b een hangi ng ar ound t he
si mul at or .

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?

What pattern would allow Geese to easily intermingle with


Ducks?
5. We need a goose adapter.

Our si mul at or ex pec t s t o see Quac k ab l e i nt er f ac es. Si nc e


geese ar en’t quac k er s (t hey ’r e honk er s), w e c an use an
adapt er t o adapt a goose t o a duc k .

6. Now geese should be able to play in the simulator, too.

A l l w e need t o do i s c r eat e a Goose and w r ap i t i n an


adapt er t hat i mpl ement s Quac k ab l e, and w e shoul d b e
good t o go.

7 . Now let’s giv e this a quick run...

Thi s t i me w hen w e r un t he si mul at or , t he l i st of ob jec t s


passed t o t he si mul at e() met hod i nc l udes a Goose w r apped
i n a duc k adapt er . The r esul t ? W e shoul d see some
honk i ng!

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.

How can we add the ability to count duck quacks without


having to change the duck classes?

Can you think of a pattern that would help?

8. We’re going to make those Quackologists happy and


giv e them some quack counts.

How ? Let ’s c r eat e a dec or at or t hat gi v es t he duc k s some


new b ehav i or (t he b ehav i or of c ount i ng) b y w r appi ng
t hem w i t h a dec or at or ob jec t . W e w on’t hav e t o c hange
t he Duc k c ode at al l .
9. We need to update the simulator to create decorated
ducks.

N ow , w e must w r ap eac h Quac k ab l e ob jec t w e i nst ant i at e


i n a Quac k Count er dec or at or . If w e don’t , w e’l l hav e duc k s
r unni ng ar ound mak i ng unc ount ed quac k s.

Y ou hav e to decorate obj ects to get decorated


behav ior.

He’s r i ght , t hat ’s t he pr ob l em w i t h w r appi ng ob jec t s: y ou


hav e t o mak e sur e t hey get w r apped or t hey don’t get t he
dec or at ed b ehav i or .

W hy don’t w e t ak e t he c r eat i on of duc k s and l oc al i ze i t i n


one pl ac e; i n ot her w or ds, l et ’s t ak e t he duc k c r eat i on and
dec or at i ng and enc apsul at e i t .

W hat pat t er n does t hat sound l i k e?

1 0. We need a factory to produce ducks!

Ok ay , w e need some qual i t y c ont r ol t o mak e sur e our


duc k s get w r apped. W e’r e goi ng t o b ui l d an ent i r e f ac t or y
just t o pr oduc e t hem. The f ac t or y shoul d pr oduc e a f ami l y
of pr oduc t s t hat c onsi st s of di f f er ent t y pes of duc k s, so
w e’r e goi ng t o use t he A b st r ac t Fac t or y Pat t er n.

N ex t w e’l l c r eat e a f ac t or y t hat c r eat es duc k s w i t hout


dec or at or s, just t o get t he hang of t he f ac t or y :

N ow l et ’s c r eat e t he f ac t or y w e r eal l y w ant , t he


Count i ngDuc k Fac t or y :
1 1 . Let’s set up the simulator to use the factory .

Rememb er how A b st r ac t Fac t or y w or k s? W e c r eat e a


pol y mor phi c met hod t hat t ak es a f ac t or y and uses i t t o
c r eat e ob jec t s. By passi ng i n di f f er ent f ac t or i es, w e get t o
use di f f er ent pr oduc t f ami l i es i n t he met hod.

W e’r e goi ng t o al t er t he si mul at e() met hod so t hat i t t ak es


a f ac t or y and uses i t t o c r eat e duc k s.

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”?

Ah, he wants to manage a flock of ducks.

Her e’s anot her good quest i on f r om Ranger Br ew er : W hy


ar e w e managi ng duc k s i ndi v i dual l y ?

W hat w e need i s a w ay t o t al k ab out c ol l ec t i ons of duc k s


and ev en sub c ol l ec t i ons of duc k s (t o deal w i t h t he f ami l y
r equest f r om Ranger Br ew er ). It w oul d al so b e ni c e i f w e
c oul d appl y oper at i ons ac r oss t he w hol e set of duc k s.

W hat pat t er n c an hel p us?

1 2. Let’s create a flock of ducks (well, actually a flock of


Quackables).

Rememb er t he Composi t e Pat t er n t hat al l ow s us t o t r eat a


c ol l ec t i on of ob jec t s i n t he same w ay as i ndi v i dual
ob jec t s? W hat b et t er c omposi t e t han a f l oc k of
Quac k ab l es!

Let ’s st ep t hr ough how t hi s i s goi ng t o w or k :

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?

1 3. Now we need to alter the simulator.

Our c omposi t e i s r eady ; w e just need some c ode t o r ound


up t he duc k s i nt o t he c omposi t e st r uc t ur e.

Let ’s gi v e i t a spi n...


SAF ET Y VER SU S
T R AN SPAR EN C Y
You might remember that in the Composite Pattern chapter
the composites (the Menus) and the leaves (the MenuItems)
had the same exact set of methods, including the add()
method. Because they had the same set of methods, we
could call methods on MenuItems that didn’t really make
sense (like trying to add something to a MenuItem by calling
add()). T he benefit of this was that the distinction between
leaves and composites was transparent: the client didn’t
have to know whether it was dealing with a leaf or a
composite; it just called the same methods on both.

Here, we’ve decided to keep the composite’s child


maintenance methods separate from the leaf nodes: that is,
only Flocks have the add() method. We know it doesn’t make
sense to try to add something to a Duck, and in this
implementation, you can’t. You can only add() to a Flock. So
this design is safer—you can’t call methods that don’t make
sense on components—but it’s less transparent. Now the
client has to know that a Quackable is a Flock in order to add
Quackables to it.

As always, there are tradeoffs when you do OO design and


you need to consider them as you create your own
composites.

Can y ou say “observ er”?

It sounds l i k e t he Quac k ol ogi st w oul d l i k e t o ob ser v e


i ndi v i dual duc k b ehav i or . That l eads us r i ght t o a pat t er n
made f or ob ser v i ng t he b ehav i or of ob jec t s: t he Ob ser v er
Pat t er n.

1 4. F irst we need an interface for our Subj ect.

Rememb er t hat t he Sub jec t i s t he ob jec t b ei ng ob ser v ed.


Let ’s c al l i t somet hi ng mor e memor ab l e—how ab out
Ob ser v ab l e? A n Ob ser v ab l e needs met hods f or
r egi st er i ng and not i f y i ng ob ser v er s. W e c oul d al so hav e a
met hod f or r emov i ng ob ser v er s, b ut w e’l l k eep t he
i mpl ement at i on si mpl e her e and l eav e t hat out .

N ow w e need t o mak e sur e al l Quac k ab l es i mpl ement t hi s


i nt er f ac e...

1 5. Now, we need to make sure all the concrete classes


that implement Quackable can handle being a
QuackObserv able.

W e c oul d appr oac h t hi s b y i mpl ement i ng r egi st r at i on


and not i f i c at i on i n eac h and ev er y c l ass (l i k e w e di d i n
Chapt er 2). But w e’r e goi ng t o do i t a l i t t l e di f f er ent l y
t hi s t i me: w e’r e goi ng t o enc apsul at e t he r egi st r at i on and
not i f i c at i on c ode i n anot her c l ass, c al l i t Ob ser v ab l e, and
c ompose i t w i t h Quac k Ob ser v ab l e. That w ay , w e onl y
w r i t e t he r eal c ode onc e and Quac k Ob ser v ab l e just needs
enough c ode t o del egat e t o t he hel per c l ass Ob ser v ab l e.
Let ’s b egi n w i t h t he Ob ser v ab l e hel per c l ass.

1 6. I ntegrate the helper Observ able with the Quackable


classes.

Thi s shoul dn’t b e t oo b ad. A l l w e need t o do i s mak e sur e


t he Quac k ab l e c l asses ar e c omposed w i t h an Ob ser v ab l e
and t hat t hey k now how t o del egat e t o i t . A f t er t hat ,
t hey ’r e r eady t o b e Ob ser v ab l es. Her e’s t he
i mpl ement at i on of Mal l ar dDuc k ; t he ot her duc k s ar e t he
same.

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:

1 7 . We’re almost there! We j ust need to work on the


Observ er side of the pattern.

W e’v e i mpl ement ed ev er y t hi ng w e need f or t he


Ob ser v ab l es; now w e need some Ob ser v er s. W e’l l st ar t
w i t h t he Ob ser v er i nt er f ac e:

N ow w e need an Ob ser v er : w her e ar e t hose


Quac k ol ogi st s?!
SH AR PEN YO U R PEN C IL
What if a 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
(sorry, all its little quackers), which may include other flocks.

Go ahead and write the Flock observer code before we go any


further.

1 8. We’re ready to observ e. Let’s update the simulator and


giv e it a try :

Thi s i s t he b i g f i nal e. Fi v e—no, si x —pat t er ns hav e c ome t oget her t o


c r eat e t hi s amazi ng Duc k Si mul at or . W i t hout f ur t her ado, w e
pr esent Duc k Si mul at or !

there are no Dumb Questions


Q: So this was a compound pattern?

A: N o, t hi s w as just a set of pat t er ns w or k i ng t oget her . A c ompound


pat t er n i s a set of a f ew pat t er ns t hat ar e c omb i ned t o sol v e a
gener al pr ob l em. W e’r e just ab out t o t ak e a l ook at t he Model -V i ew -
Cont r ol l er c ompound pat t er n; i t ’s a c ol l ec t i on of a f ew pat t er ns
t hat has b een used ov er and ov er i n many desi gn sol ut i ons.

Q: So the real beauty of Design Patterns is that I can take a


problem and start apply ing patterns to it until I hav e a solution.
Right?

A: W r ong. W e w ent t hr ough t hi s ex er c i se w i t h Duc k s t o show y ou


how pat t er ns c an w or k t oget her . You’d nev er ac t ual l y w ant t o
appr oac h a desi gn l i k e w e just di d. In f ac t , t her e may b e sol ut i ons t o
par t s of t he Duc k Si mul at or f or w hi c h some of t hese pat t er ns w er e
b i g-t i me ov er k i l l . Somet i mes just usi ng good OO desi gn pr i nc i pl es
c an sol v e a pr ob l em w el l enough on i t s ow n.

W e’r e goi ng t o t al k mor e ab out t hi s i n t he nex t c hapt er , b ut y ou


onl y w ant t o appl y pat t er ns w hen and w her e t hey mak e sense. You
nev er w ant t o st ar t out w i t h t he i nt ent i on of usi ng pat t er ns just f or
t he sak e of i t . You shoul d c onsi der t he desi gn of t he Duc k Si mul at or
t o b e f or c ed and ar t i f i c i al . But hey , i t w as f un and gav e us a good
i dea of how sev er al pat t er ns c an f i t i nt o a sol ut i on.

What did we do?


We started with a bunch of Quackables...

A goose came along and wanted to act like a Quackable too. So


w e used t he Adapter Pattern t o adapt t he goose t o a Quac k ab l e. N ow ,
y ou c an c al l quac k () on a goose w r apped i n t he adapt er and i t w i l l
honk !

Then, the Quackologists decided they wanted to count quacks.


So w e used t he Dec orator Pattern t o add a Quac k Count er dec or at or
t hat k eeps t r ac k of t he numb er of t i mes quac k () i s c al l ed, and t hen
del egat es t he quac k t o t he Quac k ab l e i t ’s w r appi ng.

But the Quackologists were worried they ’d forget to add the


QuackCounter decorator. So w e used t he Abs trac t Fac tory Pattern
t o c r eat e duc k s f or t hem. N ow , w henev er t hey w ant a duc k , t hey ask
t he f ac t or y f or one, and i t hands b ac k a dec or at ed duc k . (A nd don’t
f or get , t hey c an al so use anot her duc k f ac t or y i f t hey w ant an
undec or at ed duc k !)

We had management problems keeping track of all those ducks


and geese and quackables. So w e used t he Com pos ite Pattern t o
gr oup Quac k ab l es i nt o Fl oc k s. The pat t er n al so al l ow s t he
Quac k ol ogi st t o c r eat e sub Fl oc k s t o manage duc k f ami l i es. W e used
t he I terator Pattern i n our i mpl ement at i on b y usi ng jav a.ut i l ’s
i t er at or i n A r r ay Li st .

The Quackologists also wanted to be notified when any


Quackable quacked. So w e used t he Obs erv er Pattern t o l et t he
Quac k ol ogi st s r egi st er as Quac k ab l e Ob ser v er s. N ow t hey ’r e
not i f i ed ev er y t i me any Quac k ab l e quac k s. W e used i t er at or agai n
i n t hi s i mpl ement at i on. The Quac k ol ogi st s c an ev en use t he
Ob ser v er Pat t er n w i t h t hei r c omposi t es.

A duck’s-eye view: the class diagram


W e’v e pac k ed a l ot of pat t er ns i nt o one smal l duc k si mul at or !
Her e’s t he b i g pi c t ur e of w hat w e di d:

The King of Compound Patterns

If Elvis were a compound pattern, his name would be Model-


View-Controller, and he’d be singing a little song like this...
EAR PO W ER
Don’t just read! After all, this is a Head First book...check out this URL:

https://w w w .youtube.com/w atch?v=YYvOGPMLVDo

Sit back and give it a listen.

Design Patterns are y our key to understanding MVC.

W e w er e just t r y i ng t o w het y our appet i t e w i t h t he song. Tel l y ou


w hat , af t er y ou f i ni sh r eadi ng t hi s c hapt er , go b ac k and l i st en t o
t he song agai n—y ou’l l hav e mor e f un.

It sounds l i k e y ou’v e had a b ad r un-i n w i t h MV C b ef or e? Most of us


hav e. You’v e pr ob ab l y had ot her dev el oper s t el l y ou i t ’s c hanged
t hei r l i v es and c oul d possi b l y c r eat e w or l d peac e. It ’s a pow er f ul
c ompound pat t er n, f or sur e, and w hi l e w e c an’t c l ai m i t w i l l c r eat e
w or l d peac e, i t w i l l sav e y ou hour s of w r i t i ng c ode onc e y ou k now
i t.

But f i r st y ou hav e t o l ear n i t , r i ght ? W el l , t her e’s goi ng t o b e a b i g


di f f er enc e t hi s t i me ar ound b ec ause now y ou k now patterns !

That ’s r i ght , pat t er ns ar e t he k ey t o MV C. Lear ni ng MV C f r om t he


t op dow n i s di f f i c ul t ; not many dev el oper s suc c eed. Her e’s t he
sec r et t o l ear ni ng MV C: it’s jus t a few patterns put togeth er. W hen
y ou appr oac h l ear ni ng MV C b y l ook i ng at t he pat t er ns, al l of a
sudden i t st ar t s t o mak e sense.

Let ’s get st ar t ed. Thi s t i me ar ound, y ou’r e goi ng t o nai l MV C!

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 el l , under neat h i t al l si t s Model -V i ew -Cont r ol l er ...


A closer look...
The musi c pl ay er desc r i pt i on gi v es us a hi gh-l ev el v i ew of MV C,
b ut i t r eal l y doesn’t hel p y ou under st and t he ni t t y -gr i t t y of how
t he c ompound pat t er n w or k s, how y ou’d b ui l d one y our sel f , or w hy
i t ’s suc h a good t hi ng. Let ’s st ar t b y st eppi ng t hr ough t he
r el at i onshi ps among t he model , v i ew , and c ont r ol l er , and t hen w e’l l
t ak e sec ond l ook f r om t he per spec t i v e of Desi gn Pat t er ns.

1 . Y ou’re the user—y ou interact with the v iew.

The v i ew i s y our w i ndow t o t he model . W hen y ou do


somet hi ng t o t he v i ew (l i k e c l i c k t he Pl ay b ut t on), t hen
t he v i ew t el l s t he c ont r ol l er w hat y ou di d. It ’s t he
c ont r ol l er ’s job t o handl e t hat .

2. The controller asks the model to change its state.

The c ont r ol l er t ak es y our ac t i ons and i nt er pr et s t hem. If


y ou c l i c k a b ut t on, i t ’s t he c ont r ol l er ’s job t o f i gur e out
w hat t hat means and how t he model shoul d b e
mani pul at ed b ased on t hat ac t i on.

3. The controller may also ask the v iew to change.

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.

4. The model notifies the v iew when its state has


changed.

W hen somet hi ng c hanges i n t he model , b ased ei t her on


some ac t i on y ou t ook (l i k e c l i c k i ng a b ut t on) or some
ot her i nt er nal c hange (l i k e t he nex t song i n t he pl ay l i st
has st ar t ed), t he model not i f i es t he v i ew t hat i t s st at e has
c hanged.

5. The v iew asks the model for state.

The v i ew get s t he st at e i t di spl ay s di r ec t l y f r om t he


model . For i nst anc e, w hen t he model not i f i es t he v i ew
t hat a new song has st ar t ed pl ay i ng, t he v i ew r equest s t he
song name f r om t he model and di spl ay s i t . The v i ew mi ght
al so ask t he model f or st at e as t he r esul t of t he c ont r ol l er
r equest i ng some c hange i n t he v i ew .

there are no Dumb Questions


Q: Does the controller ev er become an observ er of the model?

A: Sur e. In some desi gns t he c ont r ol l er r egi st er s w i t h t he model and


i s not i f i ed of c hanges. Thi s c an b e t he c ase w hen somet hi ng i n t he
model di r ec t l y af f ec t s t he user i nt er f ac e c ont r ol s. For i nst anc e,
c er t ai n st at es i n t he model may di c t at e t hat some i nt er f ac e i t ems b e
enab l ed or di sab l ed. If so, i t ’s r eal l y t he c ont r ol l er ’s job t o ask t he
v i ew t o updat e i t s di spl ay ac c or di ngl y .
Q: All the controller does is take user input from the v iew and
send it to the model, correct? Why hav e it at all if that is all it
does? Why not j ust hav e the code in the v iew itself? I n most
cases isn’t the controller j ust calling a method on the model?

A: The c ont r ol l er does mor e t han just “send i t t o t he model ”; i t i s


r esponsi b l e f or i nt er pr et i ng t he i nput and mani pul at i ng t he model
b ased on t hat i nput . But y our r eal quest i on i s pr ob ab l y , “W hy c an’t
I just do t hat i n t he v i ew c ode?”

You c oul d; how ev er , y ou don’t w ant t o f or t w o r easons. Fi r st , y ou’l l


c ompl i c at e y our v i ew c ode b ec ause i t now has t w o r esponsi b i l i t i es:
managi ng t he user i nt er f ac e and deal i ng w i t h t he l ogi c of how t o
c ont r ol t he model . Sec ond, y ou’r e t i ght l y c oupl i ng y our v i ew t o t he
model . If y ou w ant t o r euse t he v i ew w i t h anot her model , f or get i t .
The c ont r ol l er separ at es t he l ogi c of c ont r ol f r om t he v i ew and
dec oupl es t he v i ew f r om t he model . By k eepi ng t he v i ew and
c ont r ol l er l oosel y c oupl ed, y ou ar e b ui l di ng a mor e f l ex i b l e and
ex t ensi b l e desi gn, one t hat c an mor e easi l y ac c ommodat e c hange
dow n t he r oad.

Understanding MVC as a set of Patterns


W e’v e al r eady suggest ed t hat t he b est pat h t o l ear ni ng MV C i s t o see
i t f or w hat i t i s: a set of pat t er ns w or k i ng t oget her i n t he same
desi gn.

Let ’s st ar t w i t h t he model : t he model uses Ob ser v er t o k eep t he


v i ew s and c ont r ol l er s updat ed on t he l at est st at e c hanges. The v i ew
and t he c ont r ol l er , on t he ot her hand, i mpl ement t he St r at egy
Pat t er n. The c ont r ol l er i s t he st r at egy of t he v i ew , and i t c an b e
easi l y ex c hanged w i t h anot her c ont r ol l er i f y ou w ant di f f er ent
b ehav i or . The v i ew i t sel f al so uses a pat t er n i nt er nal l y t o manage
t he w i ndow s, b ut t ons, and ot her c omponent s of t he di spl ay : t he
Composi t e Pat t er n.

Let ’s t ak e a c l oser l ook :

Observer

Strategy

Composite

Using MVC to control the beat...


It ’s y our t i me t o b e t he DJ. W hen y ou’r e a DJ i t ’s al l ab out t he b eat .
You mi ght st ar t y our mi x w i t h a sl ow ed, dow n-t empo gr oov e at 95
b eat s per mi nut e (BPM) and t hen b r i ng t he c r ow d up t o a f r enzi ed
1 40 BPM of t r anc e t ec hno. You’l l f i ni sh of f y our set w i t h a mel l ow
80 BPM amb i ent mi x .
How ar e y ou goi ng t o do t hat ? You hav e t o c ont r ol t he b eat , and
y ou’r e goi ng t o b ui l d t he t ool t o get y ou t her e.

Meet the Java DJ View


Let ’s st ar t w i t h t he v iew of t he t ool . The v i ew al l ow s y ou t o c r eat e a
dr i v i ng dr umb eat and t une i t s b eat s per mi nut e...

The controller is in the middle...


The controller si t s b et w een t he v i ew and model . It t ak es y our
i nput , l i k e sel ec t i ng St ar t f r om t he DJ Cont r ol menu, and t ur ns i t
i nt o an ac t i on on t he model t o st ar t t he b eat gener at i on.

Let’s not forget about the model underneath it all...


You c an’t see t he model, b ut y ou c an hear i t . The model si t s
under neat h ev er y t hi ng el se, managi ng t he b eat and dr i v i ng t he
speak er s.

Putting the pieces together


Building the pieces
Ok ay , y ou k now t he model i s r esponsi b l e f or mai nt ai ni ng al l t he
dat a, st at e, and any appl i c at i on l ogi c . So w hat ’s t he Beat Model got i n
i t ? It s mai n job i s managi ng t he b eat , so i t has st at e t hat mai nt ai ns
t he c ur r ent b eat s per mi nut e and c ode t o pl ay an audi o c l i p t o
c r eat e t he b eat t hat w e hear . It al so ex poses an i nt er f ac e t hat l et s
t he c ont r ol l er mani pul at e t he b eat and l et s t he v i ew and
c ont r ol l er ob t ai n t he model ’s st at e. A l so, don’t f or get t hat t he model
uses t he Ob ser v er Pat t er n, so w e al so need some met hods t o l et
ob jec t s r egi st er as ob ser v er s and send out not i f i c at i ons.

Let’s check out the BeatModelInterface before looking at the


implementation:

Now let’s have a look at the concrete BeatModel class

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 !

The f i r st t hi ng t o not i c e ab out t he v i ew i s t hat w e’v e i mpl ement ed


i t so t hat i t i s di spl ay ed i n t w o separ at e w i ndow s. One w i ndow
c ont ai ns t he c ur r ent BPM and t he pul se; t he ot her c ont ai ns t he
i nt er f ac e c ont r ol s. W hy ? W e w ant ed t o emphasi ze t he di f f er enc e
b et w een t he i nt er f ac e t hat c ont ai ns t he v i ew of t he model and t he
r est of t he i nt er f ac e t hat c ont ai ns t he set of user c ont r ol s. Let ’s t ak e
a c l oser l ook at t he t w o par t s of t he v i ew :

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 light show that is based on the real-time beat.

A textual view that displays a music genre based on the BPM (ambient,
downbeat, techno, etc.).

____________________________________________________________
____

____________________________________________________________
____

Implementing the View


The t w o par t s of t he v i ew —t he v i ew of t he model , and t he v i ew
w i t h t he user i nt er f ac e c ont r ol s—ar e di spl ay ed i n t w o w i ndow s,
b ut l i v e t oget her i n one Jav a c l ass. W e’l l f i r st show y ou just t he
c ode t hat c r eat es t he v i ew of t he model , w hi c h di spl ay s t he c ur r ent
BPM and t he b eat b ar . Then w e’l l c ome b ac k on t he nex t page and
show y ou just t he c ode t hat c r eat es t he user i nt er f ac e c ont r ol s,
w hi c h di spl ay s t he BPM t ex t ent r y f i el d, and t he b ut t ons.

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.

N ow , w e’l l l ook at t he c ode f or t he user i nt er f ac e c ont r ol s par t of


t he v i ew . Thi s v i ew l et s y ou c ont r ol t he model b y t el l i ng t he
c ont r ol l er w hat t o do, w hi c h i n t ur n, t el l s t he model w hat t o do.
Rememb er , t hi s c ode i s i n t he same c l ass f i l e as t he ot her v i ew c ode.
Now for the Controller
It ’s t i me t o w r i t e t he mi ssi ng pi ec e: t he c ont r ol l er . Rememb er t he
c ont r ol l er i s t he st r at egy t hat w e pl ug i nt o t he v i ew t o gi v e i t some
smar t s.

Bec ause w e ar e i mpl ement i ng t he St r at egy Pat t er n, w e need t o st ar t


w i t h an i nt er f ac e f or any St r at egy t hat mi ght b e pl ugged i nt o t he
DJ V i ew . W e’r e goi ng t o c al l i t Cont r ol l er Int er f ac e.

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?

And here’s the implementation of the controller:

Putting it all together...


W e’v e got ev er y t hi ng w e need: a model , a v i ew , and a c ont r ol l er .
N ow i t ’s t i me t o put t hem al l t oget her ! W e’r e goi ng t o see and hear
how w el l t hey w or k t oget her .

A l l w e need i s a l i t t l e c ode t o get t hi ngs st ar t ed; i t w on’t t ak e muc h:


And now for a test run...

N O TE
Make sure you have the file clip.wav at the top level of the code
folder!

Things to try

1 . Start the beat generation with the Start menu item;


notice the controller disables the item afterward.

2. Use the text entry along with the increase and


decrease buttons to change the BPM. Notice how the
v iew display reflects the changes despite the fact that
it has no logical link to the controls.

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.

5. Stop the generator. Notice how the controller disables


the Stop menu item and enables the Start menu item.

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.

Adapting the Model


For st ar t er s, w e’r e goi ng t o need t o adapt t he Hear t Model t o a
Beat Model . If w e don’t , t he v i ew w on’t b e ab l e t o w or k w i t h t he
model , b ec ause t he v i ew onl y k now s how t o get BPM(), and t he
equi v al ent hear t model met hod i s get Hear t Rat e(). How ar e w e goi ng
t o do t hi s? W e’r e goi ng t o use t he A dapt er Pat t er n, of c our se! It
t ur ns out t hat t hi s i s a c ommon t ec hni que w hen w or k i ng w i t h MV C:
use an adapt er t o adapt a model t o w or k w i t h ex i st i ng c ont r ol l er s
and v i ew s.

Her e’s t he c ode t o adapt a Hear t Model t o a Beat Model :

Now we’re ready for a HeartController


W i t h our Hear t A dapt er i n hand, w e shoul d b e r eady t o c r eat e a
c ont r ol l er and get t he v i ew r unni ng w i t h t he Hear t Model . Tal k
ab out r euse!

And that’s it! Now it’s time for some test code...

And now for a test run...


Things to try

1 . Notice that the display works great with a heart! The


beat bar looks j ust like a pulse. Because the
HeartModel also supports BPM and Beat Observ ers,
we can get beat updates j ust like with the DJ beats.

2. As the heartbeat has natural v ariation, notice the


display is updated with the new beats per minute.

3. Each time we get a BPM update, the adapter is doing


its j ob of translating getBPM() calls to getHeartRate()
calls.

4. The Start and Stop menu items are not enabled


because the controller disabled them.

5. The other buttons still work but hav e no effect


because the controller implements no ops for them.
The v iew could be changed to support the disabling of
these items.

there are no Dumb Questions


Q: I t seems like y ou are really hand-wav ing the fact that the
Composite Pattern is really in MVC. I s it really there?

A: Yes, V i r gi ni a, t her e r eal l y i s a Composi t e Pat t er n i n MV C. But ,


ac t ual l y , t hi s i s a v er y good quest i on. Today GU I pac k ages, l i k e
Sw i ng, hav e b ec ome so sophi st i c at ed t hat w e har dl y not i c e t he
i nt er nal st r uc t ur e and t he use of Composi t e i n t he b ui l di ng and
updat e of t he di spl ay . It ’s ev en har der t o see w hen w e hav e w eb
b r ow ser s t hat c an t ak e mar k up l anguage and c onv er t i t i nt o a user
i nt er f ac e.

Bac k w hen MV C w as f i r st di sc ov er ed, c r eat i ng GU Is r equi r ed a l ot


mor e manual i nt er v ent i on and t he pat t er n w as mor e ob v i ousl y
par t of t he MV C.

Q: Does the controller ev er implement any application logic?

A: N o, t he c ont r ol l er i mpl ement s b ehav i or f or t he v i ew . It i s t he


smar t s t hat t r ansl at es t he ac t i ons f r om t he v i ew t o ac t i ons on t he
model . The model t ak es t hose ac t i ons and i mpl ement s t he
appl i c at i on l ogi c t o dec i de w hat t o do i n r esponse t o t hose ac t i ons.
The c ont r ol l er mi ght hav e t o do a l i t t l e w or k t o det er mi ne w hat
met hod c al l s t o mak e on t he model , b ut t hat ’s not c onsi der ed t he
“appl i c at i on l ogi c .” The appl i c at i on l ogi c i s t he c ode t hat manages
and mani pul at es y our dat a and i t l i v es i n y our model .

Q: I ’v e alway s found the word “model” hard to wrap my head


around. I now get that it’s the guts of the application, but why
was such a v ague, hard-to-understand word used to describe
this aspect of MVC?

A: W hen MV C w as named t hey needed a w or d t hat b egan w i t h a “M”


or ot her w i se t hey c oul dn’t hav e c al l ed i t MV C.

But ser i ousl y , w e agr ee w i t h y ou. Ev er y one sc r at c hes t hei r head


and w onder s w hat a model i s. But t hen ev er y one c omes t o t he
r eal i zat i on t hat t hey c an’t t hi nk of a b et t er w or d ei t her .

Q: Y ou’v e talked a lot about the state of the model. Does this
mean it has the State Pattern in it?

A: N o, w e mean t he gener al i dea of st at e. But c er t ai nl y some model s


do use t he St at e Pat t er n t o manage t hei r i nt er nal st at es.

Q: I ’v e seen descriptions of MVC where the controller is


described as a “mediator” between the v iew and the model. I s
the controller implementing the Mediator Pattern?

A: W e hav en’t c ov er ed t he Medi at or Pat t er n (al t hough y ou’l l f i nd a


summar y of t he pat t er n i n t he appendi x ), so w e w on’t go i nt o t oo
muc h det ai l her e, b ut t he i nt ent of t he medi at or i s t o enc apsul at e
how ob jec t s i nt er ac t and pr omot e l oose c oupl i ng b y k eepi ng t w o
ob jec t s f r om r ef er r i ng t o eac h ot her ex pl i c i t l y . So, t o some degr ee,
t he c ont r ol l er c an b e seen as a medi at or , si nc e t he v i ew nev er set s
st at e di r ec t l y on t he model , b ut r at her al w ay s goes t hr ough t he
c ont r ol l er . Rememb er , how ev er , t hat t he v i ew does hav e a
r ef er enc e t o t he model t o ac c ess i t s st at e. If t he c ont r ol l er w er e
t r ul y a medi at or , t he v i ew w oul d hav e t o go t hr ough t he c ont r ol l er
t o get t he st at e of t he model as w el l .

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?

A: Yes, t he model c oul d c er t ai nl y send i t s st at e w i t h t he


not i f i c at i on, and w e c oul d do somet hi ng si mi l ar w i t h t he Beat Model
b y sendi ng just t he st at e t hat t he v i ew i s i nt er est ed i n. If y ou
r ememb er t he Ob ser v er Pat t er n c hapt er , how ev er , y ou’l l al so
r ememb er t hat t her e ar e a c oupl e of di sadv ant ages t o t hi s. If y ou
don’t , go b ac k t o Chapt er 2 and hav e a sec ond l ook . The MV C model
has b een adapt ed t o a numb er of si mi l ar model s—i n par t i c ul ar , f or
t he w eb ’s b r ow ser /ser v er env i r onment —so y ou’l l f i nd a l ot of
ex c ept i ons t o t he r ul e out t her e.

Q: I f I hav e more than one v iew, do I alway s need more than


one controller?

A: Ty pi c al l y , y ou need one c ont r ol l er per v i ew at r unt i me;


how ev er , t he same c ont r ol l er c l ass c an easi l y manage many v i ew s.

Q: The v iew is not supposed to manipulate the model; howev er,


I noticed in y our implementation that the v iew has full access to
the methods that change the model’s state. I s this dangerous?

A: You ar e c or r ec t ; w e gav e t he v i ew f ul l ac c ess t o t he model ’s set of


met hods. W e di d t hi s t o k eep t hi ngs si mpl e, b ut t her e may b e
c i r c umst anc es w her e y ou w ant t o gi v e t he v i ew ac c ess t o onl y par t
of y our model ’s A PI. Ther e’s a gr eat desi gn pat t er n t hat al l ow s y ou
t o adapt an i nt er f ac e t o pr ov i de onl y a sub set . Can y ou t hi nk of i t ?

Y es!

MV C i s so usef ul t hat i t has b een adapt ed t o many w eb f r amew or k s.


Of c our se, t he w eb w or k s di f f er ent l y t han y our st andar d
appl i c at i on, so t her e ar e sev er al di f f er ent appr oac hes t o appl y i ng
t he MV C Pat t er n t o t he w eb .

W eb appl i c at i ons hav e a c l i ent si de (t he b r ow ser ) and a ser v er si de.


Gi v en t hat , w e c an mak e di f f er ent desi gn t r adeof f s b ased on w her e
t he model , t he v i ew , and t he c ont r ol l er r esi de. In th in c lient
appr oac hes, t he model , most of t he v i ew , and t he c ont r ol l er al l
r esi de i n t he ser v er , w i t h t he b r ow ser pr ov i di ng a w ay t o di spl ay
t he v i ew , and t o get i nput f r om t he b r ow ser t o t he c ont r ol l er .
A not her appr oac h i s t he s ingle page applic ation, w her e al most al l
of t he model , v i ew , and c ont r ol l er r esi de on t he c l i ent si de. Those
ar e t he t w o ends of t he spec t r um, and y ou’l l f i nd f r amew or k s t hat
v ar y t he ex t ent t o w hi c h eac h c omponent —t hat i s t he model , t he
v i ew , and t he c ont r ol l er —r esi de on t he c l i ent or t he ser v er , al ong
w i t h hy b r i d model s w her e some c omponent s ar e shar ed ac r oss t he
c l i ent and ser v er .

Ther e ar e many popul ar w eb MV C f r amew or k s, l i k e Spr i ng W eb


MV C, Django, A SP.N ET MV C, A ngul ar JS, Emb er JS, Jav aSc r i pt MV C,
Bac k b one, and no doub t mor e on t he w ay . For t he most par t eac h
f r amew or k has i t s ow n uni que w ay i t maps t he model , t he v i ew , and
t he c ont r ol l er ac r oss t he c l i ent and t he ser v er . N ow t hat y ou k now
t he MV C Pat t er n, y ou w i l l hav e no pr ob l em adapt i ng y our
k now l edge t o w hat ev er f r amew or k y ou c hoose t o use.

Tools for your Design Toolbox


You c oul d i mpr ess any one w i t h y our desi gn t ool b ox . W ow , l ook at
al l t hose pr i nc i pl es, pat t er ns, and now , c ompound pat t er ns!
B U L L ET PO IN T S

T he Model View Controller (MVC) Pattern is a compound pattern


consisting of the Observer, Strategy, and Composite Patterns.

T he model makes use of the Observer Pattern so that it can


keep observers updated yet stay decoupled from them.

T he controller is the Strategy for the view. T he view can use


different implementations of the controller to get different
behavior.

T he view uses the Composite Pattern to implement the user


interface, which usually consists of nested components like
panels, frames, and buttons.

T hese patterns work together to decouple the three players in


the MVC model, which keeps designs clear and flexible.

T he Adapter Pattern can be used to adapt a new model to an


existing view and controller.

MVC has been adapted to the web.

T here are many web MVC frameworks with various adaptations


of the MVC pattern to fit the client/server application structure.

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”?

You could add a createGooseDuck() method to the existing Duck Factories.


Or, you could create a completely separate Factory for creating families of
Geese.

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?

Her e’s t he c ompl et e i mpl ement at i on of t he DJV i ew . It show s al l t he


MIDI c ode t o gener at e t he sound, and al l t he Sw i ng c omponent s t o
c r eat e t he v i ew . You c an al so dow nl oad t hi s c ode at
ht t ps://w w w .w i c k edl y smar t .c om. Hav e f un!

package headfirst.designpatterns.combined.djview;

public class DJTestDrive {

public static void main (String[] args) {


BeatModelInterface model = new BeatModel();
ControllerInterface controller = new BeatController(model);
}
}

The Beat Model

package headfirst.designpatterns.combined.djview;

public interface BeatModelInterface {


void initialize();

void on();

void off();

void setBPM(int bpm);


int getBPM();

void registerObserver(BeatObserver o);

void removeObserver(BeatObserver o);

void registerObserver(BPMObserver o);

void removeObserver(BPMObserver o);


}

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;

public class BeatModel implements BeatModelInterface, Runnable {


List<BeatObserver> beatObservers = new
ArrayList<BeatObserver>();
List<BPMObserver> bpmObservers = new ArrayList<BPMObserver>
();
int bpm = 90;
Thread thread;
boolean stop = false;
Clip clip;

public void initialize() {


try {
File resource = new File("clap.wav");
clip = (Clip) AudioSystem.getLine(new
Line.Info(Clip.class));

clip.open(AudioSystem.getAudioInputStream(resource));
}
catch(Exception ex) {
System.out.println("Error: Can’t load clip");
System.out.println(ex);
}
}

public void on() {


bpm = 90;
notifyBPMObservers();
thread = new Thread(this);
stop = false;
thread.start();
}

public void off() {


stopBeat();
stop = true;
}
public void run() {
while (!stop) {
playBeat();
notifyBeatObservers();
try {
Thread.sleep(60000/getBPM());
} catch (Exception e) {}
}
}

public void setBPM(int bpm) {


this.bpm = bpm;
notifyBPMObservers();
}

public int getBPM() {


return bpm;
}

public void registerObserver(BeatObserver o) {


beatObservers.add(o);
}

public void notifyBeatObservers() {


for (int i = 0; i < beatObservers.size(); i++) {
BeatObserver observer =
(BeatObserver)beatObservers.get(i);
observer.updateBeat();
}
}

public void registerObserver(BPMObserver o) {


bpmObservers.add(o);
}

public void notifyBPMObservers() {


for (int i = 0; i < bpmObservers.size(); i++) {
BPMObserver observer =
(BPMObserver)bpmObservers.get(i);
observer.updateBPM();
}
}
public void removeObserver(BeatObserver o) {
int i = beatObservers.indexOf(o);
if (i >= 0) {
beatObservers.remove(i);
}
}

public void removeObserver(BPMObserver o) {


int i = bpmObservers.indexOf(o);
if (i >= 0) {
bpmObservers.remove(i);
}
}

public void playBeat() {


clip.setFramePosition(0);
clip.start();
}

public void stopBeat() {


clip.setFramePosition(0);
clip.stop();
}
}

The View
package headfirst.designpatterns.combined.djview;

public interface BeatObserver {


void updateBeat();
}

package headfirst.designpatterns.combined.djview;

public interface BPMObserver {


void updateBPM();
}

package headfirst.designpatterns.combined.djview;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DJView implements ActionListener, BeatObserver,


BPMObserver {
BeatModelInterface model;
ControllerInterface controller;
JFrame viewFrame;
JPanel viewPanel;
BeatBar beatBar;
JLabel bpmOutputLabel;
JFrame controlFrame;
JPanel controlPanel;
JLabel bpmLabel;
JTextField bpmTextField;
JButton setBPMButton;
JButton increaseBPMButton;
JButton decreaseBPMButton;
JMenuBar menuBar;
JMenu menu;
JMenuItem startMenuItem;
JMenuItem stopMenuItem;

public DJView(ControllerInterface controller, BeatModelInterface


model) {
this.controller = controller;
this.model = model;
model.registerObserver((BeatObserver)this);
model.registerObserver((BPMObserver)this);
}
public void createView() {
// Create all Swing components here
viewPanel = new JPanel(new GridLayout(1, 2));
viewFrame = new JFrame("View");
viewFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
viewFrame.setSize(new Dimension(100, 80));
bpmOutputLabel = new JLabel("offline",
SwingConstants.CENTER);
beatBar = new BeatBar();
beatBar.setValue(0);
JPanel bpmPanel = new JPanel(new GridLayout(2, 1));
bpmPanel.add(beatBar);
bpmPanel.add(bpmOutputLabel);
viewPanel.add(bpmPanel);
viewFrame.getContentPane().add(viewPanel,
BorderLayout.CENTER);
viewFrame.pack();
viewFrame.setVisible(true);
}

public void createControls() {


// Create all Swing components here
JFrame.setDefaultLookAndFeelDecorated(true);
controlFrame = new JFrame("Control");
controlFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
controlFrame.setSize(new Dimension(100, 80));

controlPanel = new JPanel(new GridLayout(1, 2));

menuBar = new JMenuBar();


menu = new JMenu("DJ Control");
startMenuItem = new JMenuItem("Start");
menu.add(startMenuItem);
startMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
controller.start();
}
});
stopMenuItem = new JMenuItem("Stop");
menu.add(stopMenuItem);
stopMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
controller.stop();
}
});
JMenuItem exit = new JMenuItem("Quit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
menu.add(exit);
menuBar.add(menu);
controlFrame.setJMenuBar(menuBar);

bpmTextField = new JTextField(2);


bpmLabel = new JLabel("Enter BPM:", SwingConstants.RIGHT);
setBPMButton = new JButton("Set");
setBPMButton.setSize(new Dimension(10,40));
increaseBPMButton = new JButton(">>");
decreaseBPMButton = new JButton("<<");
setBPMButton.addActionListener(this);
increaseBPMButton.addActionListener(this);
decreaseBPMButton.addActionListener(this);

JPanel buttonPanel = new JPanel(new GridLayout(1, 2));


buttonPanel.add(decreaseBPMButton);
buttonPanel.add(increaseBPMButton);

JPanel enterPanel = new JPanel(new GridLayout(1, 2));


enterPanel.add(bpmLabel);
enterPanel.add(bpmTextField);
JPanel insideControlPanel = new JPanel(new GridLayout(3,
1));
insideControlPanel.add(enterPanel);
insideControlPanel.add(setBPMButton);
insideControlPanel.add(buttonPanel);
controlPanel.add(insideControlPanel);

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);
}

public void enableStopMenuItem() {


stopMenuItem.setEnabled(true);
}

public void disableStopMenuItem() {


stopMenuItem.setEnabled(false);
}
public void enableStartMenuItem() {
startMenuItem.setEnabled(true);
}

public void disableStartMenuItem() {


startMenuItem.setEnabled(false);
}

public void actionPerformed(ActionEvent event) {


if (event.getSource() == setBPMButton) {
int bpm = 90;
String bpmText = bpmTextField.getText();
if (bpmText == null || bpmText.contentEquals("")) {
bpm = 90;
} else {
bpm = Integer.parseInt(bpmTextField.getText());
}
controller.setBPM(bpm);
} else if (event.getSource() == increaseBPMButton) {
controller.increaseBPM();
} else if (event.getSource() == decreaseBPMButton) {
controller.decreaseBPM();
}
}

public void updateBPM() {


int bpm = model.getBPM();
if (bpm == 0) {
bpmOutputLabel.setText("offline");
} else {
bpmOutputLabel.setText("Current BPM: " +
model.getBPM());
}
}

public void updateBeat() {


beatBar.setValue(100);
}
}

The Controller

package headfirst.designpatterns.combined.djview;

public interface ControllerInterface {


void start();
void stop();
void increaseBPM();
void decreaseBPM();
void setBPM(int bpm);
}
package headfirst.designpatterns.combined.djview;

public class BeatController implements ControllerInterface {


BeatModelInterface model;
DJView view;

public BeatController(BeatModelInterface model) {


this.model = model;
view = new DJView(this, model);
view.createView();
view.createControls();
view.disableStopMenuItem();
view.enableStartMenuItem();
model.initialize();
}

public void start() {


model.on();
view.disableStartMenuItem();
view.enableStopMenuItem();
}

public void stop() {


model.off();
view.disableStopMenuItem();
view.enableStartMenuItem();
}

public void increaseBPM() {


int bpm = model.getBPM();
model.setBPM(bpm + 1);
}

public void decreaseBPM() {


int bpm = model.getBPM();
model.setBPM(bpm - 1);
}

public void setBPM(int bpm) {


model.setBPM(bpm);
}
}

The Heart Model

package headfirst.designpatterns.combined.djview;

public class HeartTestDrive {

public static void main (String[] args) {


HeartModel heartModel = new HeartModel();
ControllerInterface model = new HeartController(heartModel);
}
}

package headfirst.designpatterns.combined.djview;

public interface HeartModelInterface {


int getHeartRate();
void registerObserver(BeatObserver o);
void removeObserver(BeatObserver o);
void registerObserver(BPMObserver o);
void removeObserver(BPMObserver o);
}

package headfirst.designpatterns.combined.djview;

import java.util.*;

public class HeartModel implements HeartModelInterface, Runnable {


List<BeatObserver> beatObservers = new ArrayList<BeatObserver>
();
List<BPMObserver> bpmObservers = new ArrayList<BPMObserver>();
int time = 1000;
int bpm = 90;
Random random = new Random(System.currentTimeMillis());
Thread thread;

public HeartModel() {
thread = new Thread(this);
thread.start();
}

public void run() {


int lastrate = -1;

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;
}

public void registerObserver(BeatObserver o) {


beatObservers.add(o);
}

public void removeObserver(BeatObserver o) {


int i = beatObservers.indexOf(o);
if (i >= 0) {
beatObservers.remove(i);
}
}

public void notifyBeatObservers() {


for(int i = 0; i < beatObservers.size(); i++) {
BeatObserver observer =
(BeatObserver)beatObservers.get(i);
observer.updateBeat();
}
}

public void registerObserver(BPMObserver o) {


bpmObservers.add(o);
}

public void removeObserver(BPMObserver o) {


int i = bpmObservers.indexOf(o);
if (i >= 0) {
bpmObservers.remove(i);
}
}

public void notifyBPMObservers() {


for(int i = 0; i < bpmObservers.size(); i++) {
BPMObserver observer = (BPMObserver)bpmObservers.get(i);
observer.updateBPM();
}
}
}

The Heart Adapter

package headfirst.designpatterns.combined.djview;

public class HeartAdapter implements BeatModelInterface {


HeartModelInterface heart;

public HeartAdapter(HeartModelInterface heart) {


this.heart = heart;
}

public void initialize() {}

public void on() {}

public void off() {}

public int getBPM() {


return heart.getHeartRate();
}

public void setBPM(int bpm) {}

public void registerObserver(BeatObserver o) {


heart.registerObserver(o);
}

public void removeObserver(BeatObserver o) {


heart.removeObserver(o);
}

public void registerObserver(BPMObserver o) {


heart.registerObserver(o);
}

public void removeObserver(BPMObserver o) {


heart.removeObserver(o);
}
}

The Controller

package headfirst.designpatterns.combined.djview;

public class HeartController implements ControllerInterface {


HeartModelInterface model;
DJView view;

public HeartController(HeartModelInterface model) {


this.model = model;
view = new DJView(this, new HeartAdapter(model));
view.createView();
view.createControls();
view.disableStopMenuItem();
view.disableStartMenuItem();
}

public void start() {}

public void stop() {}

public void increaseBPM() {}

public void decreaseBPM() {}

public void setBPM(int bpm) {}


}
Chapter 13. Patterns in the Real
World: Better Living with Patterns

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...

Design Pattern defined


W e b et y ou’v e got a pr et t y good i dea of w hat a pat t er n i s af t er
r eadi ng t hi s b ook . But w e’v e nev er r eal l y gi v en a def i ni t i on f or a
Desi gn Pat t er n. W el l , y ou mi ght b e a b i t sur pr i sed b y t he
def i ni t i on t hat i s i n c ommon use:

N O TE
A Pattern is a solution to a problem in a context.

That ’s not t he most r ev eal i ng def i ni t i on, i s i t ? But don’t w or r y ,


w e’r e goi ng t o st ep t hr ough eac h of t hese par t s: c ont ex t , pr ob l em,
and sol ut i on:

N O TE
Example: You have a collection of objects.

The context i s t he si t uat i on i n w hi c h t he pat t er n appl i es.


Thi s shoul d b e a r ec ur r i ng si t uat i on.

The problem r ef er s t o t he goal y ou ar e t r y i ng t o ac hi ev e


i n t hi s c ont ex t , b ut i t al so r ef er s t o any c onst r ai nt s t hat
oc c ur i n t he c ont ex t .

The solution i s w hat y ou’r e af t er : a gener al desi gn t hat


any one c an appl y t hat r esol v es t he goal and set of
c onst r ai nt s.

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.

Thi s i s one of t hose def i ni t i ons t hat t ak es a w hi l e t o si nk i n, b ut


t ak e i t one st ep at a t i me. Tr y t hi nk i ng of i t l i k e t hi s:

“I f y ou find y ours elf in a c ontext w ith a problem th at h as a goal


th at is affec ted by a s et of c ons traints , th en y ou c an apply a
des ign th at res olv es th e goal and c ons traints and leads to a
s olution.”

N ow , t hi s seems l i k e a l ot of w or k just t o f i gur e out w hat a Desi gn


Pat t er n i s. A f t er al l , y ou al r eady k now t hat a Desi gn Pat t er n gi v es
y ou a sol ut i on t o a c ommon r ec ur r i ng desi gn pr ob l em. W hat i s al l
t hi s f or mal i t y get t i ng y ou? W el l , y ou’r e goi ng t o see t hat b y hav i ng
a f or mal w ay of desc r i b i ng pat t er ns w e c an c r eat e a c at al og of
pat t er ns, w hi c h has al l k i nds of b enef i t s.

You mi ght b e r i ght ; l et ’s t hi nk ab out t hi s a b i t ... W e need a problem ,


a s olution, and a c ontext:

Problem: How do I get t o w or k on t i me?

Context: I’v e l oc k ed my k ey s i n t he c ar .

Solution: Br eak t he w i ndow , get i n t he c ar , st ar t t he


engi ne, and dr i v e t o w or k .

W e hav e al l t he c omponent s of t he def i ni t i on: w e hav e a pr ob l em,


w hi c h i nc l udes t he goal of get t i ng t o w or k , and t he c onst r ai nt s of
t i me, di st anc e, and pr ob ab l y some ot her f ac t or s. W e al so hav e a
c ont ex t i n w hi c h t he k ey s t o t he c ar ar e i nac c essi b l e. A nd w e hav e
a sol ut i on t hat get s us t o t he k ey s and r esol v es b ot h t he t i me and
di st anc e c onst r ai nt s. W e must hav e a pat t er n now ! Ri ght ?

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?

Looking more closely at the Design Pattern definition


Our ex ampl e does seem t o mat c h t he Desi gn Pat t er n def i ni t i on, b ut
i t i sn’t a t r ue pat t er n. W hy ? For st ar t er s, w e k now t hat a pat t er n
needs t o appl y t o a r ec ur r i ng pr ob l em. W hi l e an ab sent -mi nded
per son mi ght l oc k hi s k ey s i n t he c ar of t en, b r eak i ng t he c ar
w i ndow doesn’t qual i f y as a sol ut i on t hat c an b e appl i ed ov er and
ov er (or at l east i sn’t l i k el y t o i f w e b al anc e t he goal w i t h anot her
c onst r ai nt : c ost ).

It al so f ai l s i n a c oupl e of ot her w ay s: f i r st , i t i sn’t easy t o t ak e t hi s


desc r i pt i on, hand i t t o someone, and hav e hi m appl y i t t o hi s ow n
uni que pr ob l em. Sec ond, w e’v e v i ol at ed an i mpor t ant b ut si mpl e
aspec t of a pat t er n: w e hav en’t ev en gi v en i t a name! W i t hout a
name, t he pat t er n doesn’t b ec ome par t of a v oc ab ul ar y t hat c an b e
shar ed w i t h ot her dev el oper s.

Luc k i l y , pat t er ns ar e not desc r i b ed and doc ument ed as a si mpl e


pr ob l em, c ont ex t , and sol ut i on; w e hav e muc h b et t er w ay s of
desc r i b i ng pat t er ns and c ol l ec t i ng t hem t oget her i nt o patterns
c atalogs .

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: Pattern descriptions, which you’ll typically find in patterns catalogs, are


usually a bit more revealing than that. We’re going to look at patterns
catalogs in detail in just a minute; they describe a lot more about a
pattern’s intent and motivation and where it might apply, along with the
solution design and the consequences (good and bad) of using it.

Q: Is it okay to slightly alter a pattern’s structure to fit my design? Or am I


going to hav e to go by the strict definition?

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.

Q: Where can I get a patterns catalog?

A: T he first and most definitive patterns catalog is Design Patterns:


Elements of Reusable Object-Oriented Softw are, by Gamma, Helm,
Johnson, and Vlissides (Addison Wesley). T his catalog lays out 23
fundamental patterns. We’ll talk a little more about this book in a few
pages.

Many other patterns catalogs are starting to be published in various domain


areas such as enterprise software, concurrent systems, and business
systems.

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.

Jim: Sur e, eac h pat t er ns c at al og t ak es a set of pat t er ns and


desc r i b es eac h i n det ai l al ong w i t h i t s r el at i onshi p t o t he ot her
pat t er ns.

Joe: A r e y ou say i ng t her e i s mor e t han one pat t er ns c at al og?

Jim: Of c our se; t her e ar e c at al ogs f or f undament al Desi gn Pat t er ns


and t her e ar e al so c at al ogs on domai n-spec i f i c pat t er ns, l i k e
ent er pr i se or di st r i b ut ed c omput i ng pat t er ns.

F rank: W hi c h c at al og ar e y ou l ook i ng at ?

Jim: Thi s i s t he c l assi c GoF c at al og; i t c ont ai ns 23 f undament al


Desi gn Pat t er ns.

F rank: GoF?

Jim: Ri ght , t hat st ands f or t he Gang of Four . The Gang of Four ar e


t he guy s t hat put t oget her t he f i r st pat t er ns c at al og.

Joe: W hat ’s i n t he c at al og?

Jim: Ther e i s a set of r el at ed pat t er ns. For eac h pat t er n t her e i s a


desc r i pt i on t hat f ol l ow s a t empl at e and spel l s out a l ot of det ai l s of
t he pat t er n. For i nst anc e, eac h pat t er n has a nam e.

F rank: W ow , t hat ’s ear t h-shat t er i ng, a name! Imagi ne t hat .

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.

F rank: Ok ay , ok ay . I w as just k i ddi ng. Go on, w hat el se i s t her e?

Jim: W el l , l i k e I w as say i ng, ev er y pat t er n f ol l ow s a t empl at e. For


eac h pat t er n w e hav e a name and a f ew sec t i ons t hat t el l us mor e
ab out t he pat t er n. For i nst anc e, t her e i s an Int ent sec t i on t hat
desc r i b es w hat t he pat t er n i s, k i nd of l i k e a def i ni t i on. Then t her e
ar e Mot i v at i on and A ppl i c ab i l i t y sec t i ons t hat desc r i b e w hen and
w her e t he pat t er n mi ght b e used.

Joe: W hat ab out t he desi gn i t sel f ?

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 .

F rank: It sounds l i k e t hey ’v e t hought of ev er y t hi ng.

Jim: Ther e’s mor e. Ther e ar e al so ex ampl es of w her e t he pat t er n has


b een used i n r eal sy st ems, as w el l as w hat I t hi nk i s one of t he most
usef ul sec t i ons: how t he pat t er n r el at es t o ot her pat t er ns.

F rank: Oh, y ou mean t hey t el l y ou t hi ngs l i k e how t he St at e and


St r at egy Pat t er ns di f f er ?

Jim: Ex ac t l y !

Joe: So Ji m, how ar e y ou ac t ual l y usi ng t he c at al og? W hen y ou hav e


a pr ob l em, do y ou go f i shi ng i n t he c at al og f or a sol ut i on?

Jim: I t r y t o get f ami l i ar w i t h al l t he pat t er ns and t hei r


r el at i onshi ps f i r st . Then, w hen I need a pat t er n, I hav e some i dea of
w hat i t i s. I go b ac k and l ook at t he Mot i v at i on and A ppl i c ab i l i t y
sec t i ons t o mak e sur e I’v e got i t r i ght . Ther e i s al so anot her r eal l y
i mpor t ant sec t i on: Consequenc es. I r ev i ew t hat t o mak e sur e t her e
w on’t b e some uni nt ended ef f ec t on my desi gn.

F rank: That mak es sense. So onc e y ou k now t he pat t er n i s r i ght ,


how do y ou appr oac h w or k i ng i t i nt o y our desi gn and
i mpl ement i ng i t ?

Jim: That ’s w her e t he c l ass di agr am c omes i n. I f i r st r ead ov er t he


St r uc t ur e sec t i on t o r ev i ew t he di agr am and t hen ov er t he
Par t i c i pant s sec t i on t o mak e sur e I under st and eac h c l ass’s r ol e.
Fr om t her e, I w or k i t i nt o my desi gn, mak i ng any al t er at i ons I need
t o mak e i t f i t . Then I r ev i ew t he Impl ement at i on and Sampl e Code
sec t i ons t o mak e sur e I k now ab out any good i mpl ement at i on
t ec hni ques or got c has I mi ght enc ount er .

Joe: I c an see how a c at al og i s r eal l y goi ng t o ac c el er at e my use of


pat t er ns!

F rank: Tot al l y . Ji m, c an y ou w al k us t hr ough a pat t er n


desc r i pt i on?

there are no Dumb Questions


Q: I s it possible to create y our own Design Patterns? Or is that
something y ou hav e to be a “patterns guru” to do?

A: Fi r st , r ememb er t hat pat t er ns ar e di sc ov er ed, not c r eat ed. So,


any one c an di sc ov er a Desi gn Pat t er n and t hen aut hor i t s
desc r i pt i on; how ev er , i t ’s not easy and doesn’t happen qui c k l y , nor
of t en. Bei ng a “pat t er ns w r i t er ” t ak es c ommi t ment .

You shoul d f i r st t hi nk ab out w hy y ou’d w ant t o—t he major i t y of


peopl e don’t aut hor pat t er ns; t hey just use t hem. How ev er , y ou
mi ght w or k i n a spec i al i zed domai n f or w hi c h y ou t hi nk new
pat t er ns w oul d b e hel pf ul , or y ou mi ght hav e c ome ac r oss a
sol ut i on t o w hat y ou t hi nk i s a r ec ur r i ng pr ob l em, or y ou may just
w ant t o get i nv ol v ed i n t he pat t er ns c ommuni t y and c ont r i b ut e t o
t he gr ow i ng b ody of w or k .

Q: I ’m game; how do I get started?

A: A s w i t h any di sc i pl i ne, t he mor e y ou k now , t he b et t er . St udy i ng


ex i st i ng pat t er ns, w hat t hey do, and how t hey r el at e t o ot her
pat t er ns i s c r uc i al . N ot onl y does i t mak e y ou f ami l i ar w i t h how
pat t er ns ar e c r af t ed, i t al so pr ev ent s y ou f r om r ei nv ent i ng t he
w heel . Fr om t her e y ou’l l w ant t o st ar t w r i t i ng y our pat t er ns on
paper , so y ou c an c ommuni c at e t hem t o ot her dev el oper s; w e’r e
goi ng t o t al k mor e ab out how t o c ommuni c at e y our pat t er ns i n a
b i t . If y ou’r e r eal l y i nt er est ed, y ou’l l w ant t o r ead t he sec t i on t hat
f ol l ow s t hese Q&A s.

Q: How do I know when I really hav e a pattern?

A: That ’s a v er y good quest i on: y ou don’t hav e a pat t er n unt i l ot her s


hav e used i t and f ound i t t o w or k . In gener al , y ou don’t hav e a
pat t er n unt i l i t passes t he “Rul e of Thr ee.” Thi s r ul e st at es t hat a
pat t er n c an b e c al l ed a pat t er n onl y i f i t has b een appl i ed i n a r eal -
w or l d sol ut i on at l east t hr ee t i mes.
So you wanna be a Design Patterns writer
Do y our homework. You need t o b e w el l v er sed i n t he ex i st i ng
pat t er ns b ef or e y ou c an c r eat e a new one. Most pat t er ns t hat
appear t o b e new , ar e, i n f ac t , just v ar i ant s of ex i st i ng pat t er ns. By
st udy i ng pat t er ns, y ou b ec ome b et t er at r ec ogni zi ng t hem, and y ou
l ear n t o r el at e t hem t o ot her pat t er ns.

Take time to reflect, ev aluate. Your ex per i enc e—t he pr ob l ems


y ou’v e enc ount er ed, and t he sol ut i ons y ou’v e used—ar e w her e i deas
f or pat t er ns ar e b or n. So t ak e some t i me t o r ef l ec t on y our
ex per i enc es and c omb t hem f or nov el desi gns t hat r ec ur .
Rememb er t hat most desi gns ar e v ar i at i ons on ex i st i ng pat t er ns
and not new pat t er ns. A nd w hen y ou do f i nd w hat l ook s l i k e a new
pat t er n, i t s appl i c ab i l i t y may b e t oo nar r ow t o qual i f y as a r eal
pat t er n.

Get y our ideas down on paper in a way others can understand.


Loc at i ng new pat t er ns i sn’t of muc h use i f ot her s c an’t mak e use of
y our f i nd; y ou need t o doc ument y our pat t er n c andi dat es so t hat
ot her s c an r ead, under st and, and appl y t hem t o t hei r ow n sol ut i on
and t hen suppl y y ou w i t h f eedb ac k . Luc k i l y , y ou don’t need t o
i nv ent y our ow n met hod of doc ument i ng y our pat t er ns. A s y ou’v e
al r eady seen w i t h t he GoF t empl at e, a l ot of t hought has al r eady
gone i nt o how t o desc r i b e pat t er ns and t hei r c har ac t er i st i c s.

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:

Organizing Design Patterns


A s t he numb er of di sc ov er ed Desi gn Pat t er ns gr ow s, i t mak es sense
t o par t i t i on t hem i nt o c l assi f i c at i ons so t hat w e c an or gani ze t hem,
nar r ow our sear c hes t o a sub set of al l Desi gn Pat t er ns, and mak e
c ompar i sons w i t hi n a gr oup of pat t er ns.

In most c at al ogs, y ou’l l f i nd pat t er ns gr ouped i nt o one of a f ew


c l assi f i c at i on sc hemes. The most w el l -k now n sc heme w as used b y
t he f i r st pat t er ns c at al og and par t i t i ons pat t er ns i nt o t hr ee
di st i nc t c at egor i es b ased on t hei r pur poses: Cr eat i onal , Behav i or al ,
and St r uc t ur al .
SH AR PEN YO U R PEN C IL

Sharpen y our pencil solution

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.

Pat t er ns ar e of t en c l assi f i ed b y a sec ond at t r i b ut e: w het her or not


t he pat t er n deal s w i t h c l asses or ob jec t s:

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.

Q: Does organizing patterns into categories really help you remember


them?

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!

Q: Why is the Decorator Pattern in the structural category? I would hav e


thought of that as a behav ioral pattern; after all, it adds behav ior!

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...

Guru: S tudent, y ou look troubled.

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...

S tud e nt: After learning m uc h about patterns , I ’v e jus t been told


th at eac h pattern fits into one of th ree c las s ific ations : s truc tural,
beh av ioral, or c reational. Wh y do w e need th es e c las s ific ations ?

Guru: Wh enev er w e h av e a large c ollec tion of any th ing, w e


naturally find c ategories to fit th os e th ings into. I t h elps us to th ink
of th e item s at a m ore abs trac t lev el.

S tud e nt: Guru; c an y ou giv e m e an exam ple?

Guru: Of c ours e. Tak e autom obiles ; th ere are m any different


m odels of autom obiles and w e naturally put th em into c ategories
lik e ec onom y c ars , s ports c ars , S UVs , truc k s , and luxury c ars .

Guru: You look s h oc k ed; does th is not m ak e s ens e?

S tud e nt: Guru, it m ak es a lot of s ens e, but I am s h oc k ed y ou k now


s o m uc h about c ars !

Guru: I c an’t relate e v e ry th ing to lotus flow ers or ric e bow ls .


Now , m ay I c ontinue?

S tud e nt: Yes , y es , I ’m s orry , pleas e c ontinue.

Guru: Onc e y ou h av e c las s ific ations or c ategories , y ou c an eas ily


talk about th e different groupings : “I f y ou’re doing th e m ountain
driv e from S ilic on Valley to S anta Cruz , a s ports c ar w ith good
h andling is th e bes t option.” Or, “With th e w ors ening oil s ituation,
y ou really w ant to buy a ec onom y c ar; th ey ’re m ore fuel-effic ient.”

S tud e nt: S o by h av ing c ategories , w e c an talk about a s et of


patterns as a group. We m igh t k now w e need a c reational pattern,
w ith out k now ing exac tly w h ic h one, but w e c an s till talk about
c reational patterns .

Guru: Yes , and it als o giv es us a w ay to c om pare a m em ber to th e


res t of th e c ategory . For exam ple, “Th e Mini really is th e m os t s ty lis h
c om pac t c ar around,” or to narrow our s earc h , “I need a fuel-effic ient
c ar.”

S tud e nt: I s ee. S o I m igh t s ay th at th e Adapter Pattern is th e bes t


s truc tural pattern for c h anging an objec t’s interfac e.

Guru: Yes . We als o c an us e c ategories for one m ore purpos e: to


launc h into new territory . For ins tanc e, “We really w ant to deliv er a
s ports c ar w ith Ferrari perform anc e at Honda pric es .”

S tud e nt: Th at s ounds lik e a death trap.

Guru: I ’m s orry , I did not h ear y ou, s tudent.

S tud e nt: Uh , I s aid “I s ee th at.”

S tud e nt: S o c ategories giv e us a w ay to th ink about th e w ay


groups of patterns relate and h ow patterns w ith in a group relate to
one anoth er. Th ey als o giv e us a w ay to extrapolate to new patterns .
But w h y are th ere th ree c ategories and not four or fiv e?

Guru: Ah , lik e s tars in th e nigh t s k y , th ere are as m any c ategories


as y ou w ant to s ee. Th ree is a c onv enient num ber and a num ber th at
m any people h av e dec ided m ak es for a nic e grouping of patterns .
But oth ers h av e s ugges ted four, fiv e, or m ore.
Thinking in Patterns
Cont ex t s, c onst r ai nt s, f or c es, c at al ogs, c l assi f i c at i ons...b oy , t hi s i s
st ar t i ng t o sound mi ght y ac ademi c . Ok ay , al l t hat st uf f i s i mpor t ant
and k now l edge i s pow er . But , l et ’s f ac e i t , i f y ou under st and t he
ac ademi c st uf f and don’t hav e t he experienc e and prac tic e usi ng
pat t er ns, t hen i t ’s not goi ng t o mak e muc h di f f er enc e i n y our l i f e.

Her e’s a qui c k gui de t o hel p y ou st ar t t o th ink in patterns . W hat do


w e mean b y t hat ? W e mean b ei ng ab l e t o l ook at a desi gn and see
w her e pat t er ns nat ur al l y f i t and w her e t hey don’t .

Keep it simple (KISS)

Fi r st of al l , w hen y ou desi gn, sol v e t hi ngs i n t he si mpl est w ay


possi b l e. Your goal shoul d b e si mpl i c i t y , not “how c an I appl y a
pat t er n t o t hi s pr ob l em?” Don’t f eel l i k e y ou ar en’t a sophi st i c at ed
dev el oper i f y ou don’t use a pat t er n t o sol v e a pr ob l em. Ot her
dev el oper s w i l l appr ec i at e and admi r e t he si mpl i c i t y of y our
desi gn. That sai d, somet i mes t he b est w ay t o k eep y our desi gn
si mpl e and f l ex i b l e i s t o use a pat t er n.

Design Patterns aren’t a magic bullet; in fact, they’re not even a


bullet!

Pat t er ns, as y ou k now , ar e gener al sol ut i ons t o r ec ur r i ng pr ob l ems.


Pat t er ns al so hav e t he b enef i t of b ei ng w el l t est ed b y l ot s of
dev el oper s. So, w hen y ou see a need f or one, y ou c an sl eep w el l
k now i ng many dev el oper s hav e b een t her e b ef or e and sol v ed t he
pr ob l em usi ng si mi l ar t ec hni ques.

How ev er , pat t er ns ar en’t a magi c b ul l et . You c an’t pl ug one i n,


c ompi l e, and t hen t ak e an ear l y l unc h. To use pat t er ns, y ou al so
need t o t hi nk t hr ough t he c onsequenc es f or t he r est of y our desi gn.

You know you need a pattern when...

A h...t he most i mpor t ant quest i on: w hen do y ou use a pat t er n? A s y ou


appr oac h y our desi gn, i nt r oduc e a pat t er n w hen y ou’r e sur e i t
addr esses a pr ob l em i n y our desi gn. If a si mpl er sol ut i on mi ght
w or k , gi v e t hat c onsi der at i on b ef or e y ou c ommi t t o usi ng a pat t er n.

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 !

Ther e i s one si t uat i on i n w hi c h y ou’l l w ant t o use a pat t er n ev en i f


a si mpl er sol ut i on w oul d w or k : w hen y ou ex pec t aspec t s of y our
sy st em t o v ar y . A s w e’v e seen, i dent i f y i ng ar eas of c hange i n y our
desi gn i s usual l y a good si gn t hat a pat t er n i s needed. Just mak e sur e
y ou ar e addi ng pat t er ns t o deal w i t h prac tic al c h ange t hat i s l i k el y
t o happen, not h y poth etic al c h ange t hat may happen.

Desi gn t i me i sn’t t he onl y t i me y ou w ant t o c onsi der i nt r oduc i ng


pat t er ns; y ou’l l al so w ant t o do so at r ef ac t or i ng t i me.

Refactoring time is Patterns time!

Refac toring i s t he pr oc ess of mak i ng c hanges t o y our c ode t o


i mpr ov e t he w ay i t i s or gani zed. The goal i s t o i mpr ov e i t s
st r uc t ur e, not c hange i t s b ehav i or . Thi s i s a gr eat t i me t o
r eex ami ne y our desi gn t o see i f i t mi ght b e b et t er st r uc t ur ed w i t h
pat t er ns. For i nst anc e, c ode t hat i s f ul l of c ondi t i onal st at ement s
mi ght si gnal t he need f or t he St at e Pat t er n. Or , i t may b e t i me t o
c l ean up c onc r et e dependenc i es w i t h Fac t or y . Ent i r e b ook s hav e
b een w r i t t en on t he t opi c of r ef ac t or i ng w i t h pat t er ns, and as y our
sk i l l s gr ow , y ou’l l w ant t o st udy t hi s ar ea mor e.

Take out what you don’t really need. Don’t be afraid to remove a
Design Pattern from your design.

N o one ev er t al k s ab out w hen t o r emov e a pat t er n. You’d t hi nk i t


w as b l asphemy ! N ah, w e’r e al l adul t s her e; w e c an t ak e i t .

So w hen do y ou r emov e a pat t er n? W hen y our sy st em has b ec ome


c ompl ex and t he f l ex i b i l i t y y ou pl anned f or i sn’t needed. In ot her
w or ds, w hen a si mpl er sol ut i on w i t hout t he pat t er n w oul d b e
b et t er .

If you don’t need it now, don’t do it now.


Desi gn Pat t er ns ar e pow er f ul , and i t ’s easy t o see al l k i nds of w ay s
t hey c an b e used i n y our c ur r ent desi gns. Dev el oper s nat ur al l y
l ov e t o c r eat e b eaut i f ul ar c hi t ec t ur es t hat ar e r eady t o t ak e on
c hange f r om any di r ec t i on.

Resi st t he t empt at i on. If y ou hav e a pr ac t i c al need t o suppor t


c hange i n a desi gn t oday , go ahead and empl oy a pat t er n t o handl e
t hat c hange. How ev er , i f t he r eason i s onl y hy pot het i c al , don’t add
t he pat t er n; i t w i l l onl y add c ompl ex i t y t o y our sy st em, and y ou
mi ght nev er need i t !
G U R U A N D ST U D EN T...

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.

Student: So I shouldn’t build my designs from patterns?

Guru: That should not be your goal w hen beginning a design. Let patterns
emerge naturally as your design progresses.

Student: If patterns are so great, w hy should I be so careful about using


them?

Guru: Patterns can introduce complexity, and w e never w ant complexity


w here it is not needed. But patterns are pow erful w hen used w here they
are needed. As you already know , patterns are proven design experience
that can be used to avoid common mistakes. They’re also a shared
vocabulary for communicating our design to others.

Student: Well, w hen do w e know it’s okay to introduce design patterns?

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.

Student: I guess my learning is going to continue even though I already


understand a lot of patterns.

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.

Student: Wait a minute, you mean I don’t know them ALL?

Guru: Student, you’ve learned the fundamental patterns; you’re going to


find there are many more, including patterns that just apply to particular
domains such as concurrent systems and enterprise systems. But now
that you know the basics, you’re in good shape to learn them.

Your Mind on Patterns

The Beginner uses patterns ev ery where. Thi s i s good: t he


b egi nner get s l ot s of ex per i enc e w i t h and pr ac t i c e usi ng pat t er ns.
The b egi nner al so t hi nk s, “The mor e pat t er ns I use, t he b et t er t he
desi gn.” The b egi nner w i l l l ear n t hi s i s not so, t hat al l desi gns
shoul d b e as si mpl e as possi b l e. Compl ex i t y and pat t er ns shoul d
onl y b e used w her e t hey ar e needed f or pr ac t i c al ex t ensi b i l i t y .

As learning progresses, the I ntermediate mind starts to see


where patterns are needed and where they aren’t. The
i nt er medi at e mi nd st i l l t r i es t o f i t t oo many squar e pat t er ns i nt o
r ound hol es, b ut al so b egi ns t o see t hat pat t er ns c an b e adapt ed t o
f i t si t uat i ons w her e t he c anoni c al pat t er n doesn’t f i t .
The Zen mind is able to see patterns where they fit naturally .
The Zen mi nd i s not ob sessed w i t h usi ng pat t er ns; r at her , i t l ook s
f or si mpl e sol ut i ons t hat b est sol v e t he pr ob l em. The Zen mi nd
t hi nk s i n t er ms of t he ob jec t pr i nc i pl es and t hei r t r adeof f s. W hen a
need f or a pat t er n nat ur al l y ar i ses, t he Zen mi nd appl i es i t
k now i ng w el l t hat i t may r equi r e adapt at i on. The Zen mi nd al so
sees r el at i onshi ps t o si mi l ar pat t er ns and under st ands t he
sub t l et i es of di f f er enc es i n t he i nt ent of r el at ed pat t er ns. Th e Zen
m ind is als o a Beginner m ind—i t doesn’t l et al l t hat pat t er n
k now l edge ov er l y i nf l uenc e desi gn dec i si ons.

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.

Of course we want y ou to use Design Patterns!


But w e w ant y ou t o b e a good OO desi gner ev en mor e.

W hen a desi gn sol ut i on c al l s f or a pat t er n, y ou get t he b enef i t s of


usi ng a sol ut i on t hat has b een t i me-t est ed b y l ot s of dev el oper s.
You’r e al so usi ng a sol ut i on t hat i s w el l doc ument ed and t hat ot her
dev el oper s ar e goi ng t o r ec ogni ze (y ou k now , t hat w hol e shar ed
v oc ab ul ar y t hi ng).

How ev er , w hen y ou use Desi gn Pat t er ns, t her e c an al so b e a


dow nsi de. Desi gn Pat t er ns of t en i nt r oduc e addi t i onal c l asses and
ob jec t s, and so t hey c an i nc r ease t he c ompl ex i t y of y our desi gns.
Desi gn Pat t er ns c an al so add mor e l ay er s t o y our desi gn, w hi c h adds
not onl y c ompl ex i t y , b ut al so i nef f i c i enc y .

A l so, usi ng a Desi gn Pat t er n c an somet i mes b e out r i ght ov er k i l l .


Many t i mes y ou c an f al l b ac k on y our desi gn pr i nc i pl es and f i nd a
muc h si mpl er sol ut i on t o sol v e t he same pr ob l em. If t hat happens,
don’t f i ght i t . U se t he si mpl er sol ut i on.

Don’t l et us di sc our age y ou, t hough. W hen a Desi gn Pat t er n i s t he


r i ght t ool f or t he job , t he adv ant ages ar e many .

Don’t forget the power of the shared vocabulary


W e’v e spent so muc h t i me i n t hi s b ook di sc ussi ng OO nut s and b ol t s
t hat i t ’s easy t o f or get t he human si de of Desi gn Pat t er ns—t hey
don’t just hel p l oad y our b r ai n w i t h sol ut i ons, t hey al so gi v e y ou a
shar ed v oc ab ul ar y w i t h ot her dev el oper s. Don’t under est i mat e t he
pow er of a shar ed v oc ab ul ar y , i t ’s one of t he bigges t benefits of
Desi gn Pat t er ns.

Just t hi nk , somet hi ng has c hanged si nc e t he l ast t i me w e t al k ed


ab out shar ed v oc ab ul ar i es; y ou’v e now st ar t ed t o b ui l d up qui t e a
v oc ab ul ar y of y our ow n! N ot t o ment i on, y ou hav e al so l ear ned a
f ul l set of OO desi gn pr i nc i pl es f r om w hi c h y ou c an easi l y
under st and t he mot i v at i on and w or k i ngs of any new pat t er ns y ou
enc ount er .

N ow t hat y ou’v e got t he Desi gn Pat t er n b asi c s dow n, i t ’s t i me f or


y ou t o go out and spr ead t he w or d t o ot her s. W hy ? Bec ause w hen
y our f el l ow dev el oper s k now pat t er ns and use a shar ed v oc ab ul ar y
as w el l , i t l eads t o b et t er desi gns and b et t er c ommuni c at i on, and,
b est of al l , i t ’l l sav e y ou a l ot of t i me t hat y ou c an spend on c ool er
t hi ngs.

Top fiv e way s to share y our v ocabulary

1 . I n design meetings: W hen y ou meet w i t h y our t eam t o


di sc uss a sof t w ar e desi gn, use desi gn pat t er ns t o hel p st ay
“i n t he desi gn” l onger . Di sc ussi ng desi gns f r om t he
per spec t i v e of Desi gn Pat t er ns and OO pr i nc i pl es k eeps
y our t eam f r om get t i ng b ogged dow n i n i mpl ement at i on
det ai l s and pr ev ent s many mi sunder st andi ngs.

2. With other dev elopers: U se pat t er ns i n y our di sc ussi ons


w i t h ot her dev el oper s. Thi s hel ps ot her dev el oper s l ear n
ab out new pat t er ns and b ui l ds a c ommuni t y . The b est
par t ab out shar i ng w hat y ou’v e l ear ned i s t hat gr eat
f eel i ng w hen someone el se “get s i t ”!

3. I n architecture documentation: W hen y ou w r i t e


ar c hi t ec t ur al doc ument at i on, usi ng pat t er ns w i l l r educ e
t he amount of doc ument at i on y ou need t o w r i t e and gi v es
t he r eader a c l ear er pi c t ur e of t he desi gn.

4. I n code comments and naming conv entions: W hen


y ou’r e w r i t i ng c ode, c l ear l y i dent i f y t he pat t er ns y ou’r e
usi ng i n c omment s. A l so, c hoose c l ass and met hod names
t hat r ev eal any pat t er ns under neat h. Ot her dev el oper s
w ho hav e t o r ead y our c ode w i l l t hank y ou f or al l ow i ng
t hem t o qui c k l y under st and y our i mpl ement at i on.

5. To groups of interested dev elopers: Shar e y our


k now l edge. Many dev el oper s hav e hear d ab out pat t er ns
b ut don’t hav e a good under st andi ng of w hat t hey ar e.
V ol unt eer t o gi v e a b r ow n-b ag l unc h on pat t er ns or a t al k
at y our l oc al user gr oup.
Cruisin’ Objectville with the Gang of Four
You w on’t f i nd t he Jet s or Shar k s hangi ng ar ound Ob jec t v i l l e, b ut
y ou w i l l f i nd t he Gang of Four . A s y ou’v e pr ob ab l y not i c ed, y ou
c an’t get f ar i n t he W or l d of Pat t er ns w i t hout r unni ng i nt o t hem.
So, w ho i s t hi s my st er i ous gang?

Put si mpl y , “t he GoF,” w hi c h i nc l udes Er i c h Gamma, Ri c har d Hel m,


Ral ph Johnson, and John V l i ssi des, i s t he gr oup of guy s w ho put
t oget her t he f i r st pat t er ns c at al og and i n t he pr oc ess, st ar t ed an
ent i r e mov ement i n t he sof t w ar e f i el d!

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 ...

Your journey has just begun...


N ow t hat y ou’r e on t op of Desi gn Pat t er ns and r eady t o di g deeper ,
w e’v e got t hr ee def i ni t i v e t ex t s t hat y ou need t o add t o y our
b ook shel f ...

The definitive Design Patterns text


Thi s i s t he b ook t hat k i c k ed of f t he ent i r e f i el d of Desi gn Pat t er ns
w hen i t w as r el eased i n 1 995. You’l l f i nd al l t he f undament al
pat t er ns her e. In f ac t , t hi s b ook i s t he b asi s f or t he set of pat t er ns
w e used i n Head Firs t Des ign Patterns .

You w on’t f i nd t hi s b ook t o b e t he l ast w or d on Desi gn Pat t er ns—t he


f i el d has gr ow n sub st ant i al l y si nc e i t s pub l i c at i on—b ut i t i s t he
f i r st and most def i ni t i v e.

Pi c k i ng up a c opy of Des ign Patterns i s a gr eat w ay t o st ar t


ex pl or i ng pat t er ns af t er Head Fi r st .
The definitive Patterns texts

Pat t er ns di dn’t st ar t w i t h t he GoF; t hey st ar t ed w i t h Chr i st opher


A l ex ander , a pr of essor of ar c hi t ec t ur e at Ber k el ey —t hat ’s r i ght ,
A l ex ander i s an arc h itec t, not a c omput er sc i ent i st . A l ex ander
i nv ent ed pat t er ns f or b ui l di ng l i v i ng ar c hi t ec t ur es (l i k e houses,
t ow ns, and c i t i es).

The nex t t i me y ou’r e i n t he mood f or some deep, engagi ng r eadi ng,


pi c k up Th e Tim eles s Way of Building and A Pattern Language.
You’l l see t he t r ue b egi nni ngs of Desi gn Pat t er ns and r ec ogni ze t he
di r ec t anal ogi es b et w een c r eat i ng “l i v i ng ar c hi t ec t ur e” and
f l ex i b l e, ex t ensi b l e sof t w ar e.

So gr ab a c up of St ar b uzz c of f ee, si t b ac k , and enjoy ...

Other Design Patterns resources


You’r e goi ng t o f i nd t her e i s a v i b r ant , f r i endl y c ommuni t y of
pat t er ns user s and w r i t er s out t her e and t hey ’r e gl ad t o hav e y ou
joi n t hem. Her e ar e a f ew r esour c es t o get y ou st ar t ed...

Websites

The Portland Patterns Repository , r un b y W ar d Cunni ngham, i s a


w i k i dev ot ed t o al l t hi ngs r el at ed t o pat t er ns. You’l l f i nd t hr eads of
di sc ussi on on ev er y t opi c y ou c an t hi nk of r el at ed t o pat t er ns and
OO sy st ems.

c 2.c om/c gi /w i k i ?W el c omeV i si t or s

The Hillside Group f ost er s c ommon pr ogr ammi ng and desi gn


pr ac t i c es and pr ov i des a c ent r al r esour c e f or pat t er ns w or k . The
si t e i nc l udes i nf or mat i on on many pat t er ns-r el at ed r esour c es suc h
as ar t i c l es, b ook s, mai l i ng l i st s, and t ool s.
hi l l si de.net

O’Reilly Online Learning pr ov i des onl i ne desi gn pat t er ns b ook s,


c our ses, and l i v e t eac hi ng. You’l l al so f i nd a desi gn pat t er ns
b oot c amp c our se b ased on t hi s b ook .

or ei l l y .c om

Conferences and Workshops

If y ou’d l i k e t o i nt er ac t w i t h t he pat t er ns c ommuni t y , b e sur e t o


c hec k out t he many pat t er ns-r el at ed c onf er enc es and w or k shops.
The Hi l l si de si t e mai nt ai ns a c ompl et e l i st . Chec k out Pat t er n
Languages of Pr ogr ams (PLoP) and t he A CM Conf er enc e on Ob jec t -
Or i ent ed Sy st ems, Languages and A ppl i c at i ons (OOPSLA ), w hi c h i s
now par t of t he SPLA SH c onf er enc e.

Other Resources

W e’d b e r emi ss i f w e di dn’t ment i on Googl e, St ac k Ov er f l ow , Quor a,


and many ot her si t es and ser v i c es as good pl ac es t o ask quest i ons,
f i nd answ er s, and di sc uss desi gn pat t er ns. A s w i t h any t hi ng on t he
w eb , al w ay s doub l e-c hec k t he i nf or mat i on y ou r ec ei v e.

The Patterns Zoo


A s y ou’v e just seen, pat t er ns di dn’t st ar t w i t h sof t w ar e; t hey st ar t ed
w i t h t he ar c hi t ec t ur e of b ui l di ngs and t ow ns. In f ac t , t he pat t er ns
c onc ept c an b e appl i ed i n many di f f er ent domai ns. Tak e a w al k
ar ound t he Pat t er ns Zoo t o see a f ew ...
Annihilating evil with Anti-Patterns
The U ni v er se just w oul dn’t b e c ompl et e i f w e had pat t er ns and no
ant i -pat t er ns, now w oul d i t ?

If a Desi gn Pat t er n gi v es y ou a gener al sol ut i on t o a r ec ur r i ng


pr ob l em i n a par t i c ul ar c ont ex t , t hen w hat does an ant i -pat t er n
gi v e y ou?

N O TE
An Anti-Pattern tells you how to go from a problem to a BAD
solution.

You’r e pr ob ab l y ask i ng y our sel f , “W hy on ear t h w oul d any one


w ast e t hei r t i me doc ument i ng b ad sol ut i ons?”

Thi nk ab out i t l i k e t hi s: i f t her e i s a r ec ur r i ng b ad sol ut i on t o a


c ommon pr ob l em, t hen b y doc ument i ng i t w e c an pr ev ent ot her
dev el oper s f r om mak i ng t he same mi st ak e. A f t er al l , av oi di ng b ad
sol ut i ons c an b e just as v al uab l e as f i ndi ng good ones!

Let ’s l ook at t he el ement s of an ant i -pat t er n:

An anti-pattern tells y ou why a bad solution is attractiv e. Let ’s


f ac e i t , no one w oul d c hoose a b ad sol ut i on i f t her e w asn’t
somet hi ng ab out i t t hat seemed at t r ac t i v e up f r ont . One of t he
b i ggest job s of t he ant i -pat t er n i s t o al er t y ou t o t he seduc t i v e
aspec t of t he sol ut i on.

An anti-pattern tells y ou why that solution in the long term is


bad. In or der t o under st and w hy i t ’s an ant i -pat t er n, y ou’v e got t o
under st and how i t ’s goi ng t o hav e a negat i v e ef f ec t dow n t he r oad.
The ant i -pat t er n desc r i b es w her e y ou’l l get i nt o t r oub l e usi ng t he
sol ut i on.

An anti-pattern suggests other applicable patterns that may


prov ide good solutions. To b e t r ul y hel pf ul , an ant i -pat t er n needs
t o poi nt y ou i n t he r i ght di r ec t i on; i t shoul d suggest ot her
possi b i l i t i es t hat may l ead t o good sol ut i ons.

Let ’s hav e a l ook at an ant i -pat t er n.


Tools for your Design Toolbox
You’v e r eac hed t hat poi nt w her e y ou’v e out gr ow n us. N ow ’s t he
t i me t o go out i n t he w or l d and ex pl or e pat t er ns on y our ow n...
B U L L ET PO IN T S

Let Design Patterns emerge in your designs; don’t force them in


just for the sake of using a pattern.

Design Patterns aren’t set in stone; adapt and tweak them to


meet your needs.

Always use the simplest solution that meets your needs, even if
it doesn’t include a pattern.

Study Design Patterns catalogs to familiarize yourself with


patterns and the relationships among them.

Pattern classifications (or categories) provide groupings for


patterns. When they help, use them.

You need to be committed to be a patterns writer: it takes time


and patience, and you have to be willing to do lots of
refinement.

Remember, most patterns you encounter will be adaptations of


existing patterns, not new patterns.

Build your team’s shared vocabulary. T his is one of the most


powerful benefits of using patterns.

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...

Boy, it’s been great having you in Objectville.


W e’r e goi ng t o mi ss y ou, f or sur e. But don’t w or r y —b ef or e y ou k now
i t , t he nex t Head Fi r st b ook w i l l b e out and y ou c an v i si t agai n.
W hat ’s t he nex t b ook , y ou ask ? Hmmm, good quest i on! W hy don’t
y ou hel p us dec i de? Send emai l t o
b ook suggest i ons@w i c k edl y smar t .c om.
W H O D O ES W H AT ? SO L U T IO N
Match each pattern with its description:
Appendix A. Leftover Patterns

Not ev ery one can be the most popular. A l ot has c hanged i n t he


l ast 25+ y ear s. Si nc e Des ign Patterns : Elem ents of Reus able Objec t-
Oriented S oftw are f i r st c ame out , dev el oper s hav e appl i ed t hese
pat t er ns t housands of t i mes. The pat t er ns w e summar i ze i n t hi s
appendi x ar e f ul l -f l edged, c ar d-c ar r y i ng, of f i c i al GoF pat t er ns, b ut
ar en’t used as of t en as t he pat t er ns w e’v e ex pl or ed so f ar . But t hese
pat t er ns ar e aw esome i n t hei r ow n r i ght , and i f y our si t uat i on c al l s
f or t hem, y ou shoul d appl y t hem w i t h y our head hel d hi gh. Our goal
i n t hi s appendi x i s t o gi v e y ou a hi gh-l ev el i dea of w hat t hese
pat t er ns ar e al l ab out .

Bridge
Use the Bridge Pattern to v ary not only y our implementations,
but also y our abstractions.

A scenario

Imagi ne y ou’r e w r i t i ng t he c ode f or a new er gonomi c and user -


f r i endl y r emot e c ont r ol f or TV s. You al r eady k now t hat y ou’v e got
t o use good ob jec t -or i ent ed t ec hni ques b ec ause w hi l e t he r emot e i s
b ased on t he same abs trac tion, t her e w i l l b e l ot s of im plem entations
—one f or eac h model of TV .

Your dilemma

You k now t hat t he r emot e’s user i nt er f ac e w on’t b e r i ght t he f i r st


t i me. In f ac t , y ou ex pec t t hat t he pr oduc t w i l l b e r ef i ned many
t i mes as usab i l i t y dat a i s c ol l ec t ed on t he r emot e c ont r ol .

So y our di l emma i s t hat t he r emot es ar e goi ng t o c hange and t he TV s


ar e goi ng t o c hange. You’v e al r eady abs trac ted t he user i nt er f ac e so
t hat y ou c an v ar y t he im plem entation ov er t he many TV s y our
c ust omer s w i l l ow n. But y ou ar e al so goi ng t o need t o v ary th e
abs trac tion b ec ause i t i s goi ng t o c hange ov er t i me as t he r emot e i s
i mpr ov ed b ased on t he user f eedb ac k .

So how ar e y ou goi ng t o c r eat e an ob jec t -or i ent ed desi gn t hat al l ow s


y ou t o v ar y t he i mpl ement at i on and t he ab st r ac t i on?

Why use the Bridge Pattern?


The Br i dge Pat t er n al l ow s y ou t o v ar y t he i mpl ement at i on and t he
ab st r ac t i on b y pl ac i ng t he t w o i n separ at e c l ass hi er ar c hi es.

N ow y ou hav e t w o hi er ar c hi es, one f or t he r emot es and a separ at e


one f or pl at f or m-spec i f i c TV i mpl ement at i ons. The b r i dge al l ow s
y ou t o v ar y ei t her si de of t he t w o hi er ar c hi es i ndependent l y .

B R ID G E B EN EF IT S

Decouples an implementation so that it is not bound


permanently to an interface.

Abstraction and implementation can be extended independently.

Changes to the concrete abstraction classes don’t affect the


client.

B R ID G E U SES AN D D R AW B AC K S

Useful in graphics and windowing systems that need to run over


multiple platforms.

Useful any time you need to vary an interface and an


implementation in different ways.

Increases complexity.

Builder
Use the Builder Pattern to encapsulate the construction of a
product and allow it to be constructed in steps.

A scenario

You’v e just b een ask ed t o b ui l d a v ac at i on pl anner f or Pat t er nsl and,


a new t heme par k just out si de of Ob jec t v i l l e. Par k guest s c an
c hoose a hot el and v ar i ous t y pes of admi ssi on t i c k et s, mak e
r est aur ant r eser v at i ons, and ev en b ook spec i al ev ent s. To c r eat e a
v ac at i on pl anner , y ou need t o b e ab l e t o c r eat e st r uc t ur es l i k e t hi s:

You need a flexible design

Eac h guest ’s pl anner c an v ar y i n t he numb er of day s and t y pes of


ac t i v i t i es i t i nc l udes. For i nst anc e, a l oc al r esi dent mi ght not need
a hot el , b ut w ant s t o mak e di nner and spec i al ev ent r eser v at i ons.
A not her guest mi ght b e f l y i ng i nt o Ob jec t v i l l e and needs a hot el ,
di nner r eser v at i ons, and admi ssi on t i c k et s.

So, y ou need a f l ex i b l e dat a st r uc t ur e t hat c an r epr esent guest


pl anner s and al l t hei r v ar i at i ons; y ou al so need t o f ol l ow a
sequenc e of pot ent i al l y c ompl ex st eps t o c r eat e t he pl anner . How
c an y ou pr ov i de a w ay t o c r eat e t he c ompl ex st r uc t ur e w i t hout
mi x i ng i t w i t h t he st eps f or c r eat i ng i t ?

Why use the Builder Pattern?


Rememb er It er at or ? W e enc apsul at ed t he i t er at i on i nt o a separ at e
ob jec t and hi d t he i nt er nal r epr esent at i on of t he c ol l ec t i on f r om
t he c l i ent . It ’s t he same i dea her e: w e enc apsul at e t he c r eat i on of
t he t r i p pl anner i n an ob jec t (l et ’s c al l i t a b ui l der ), and hav e our
c l i ent ask t he b ui l der t o c onst r uc t t he t r i p pl anner st r uc t ur e f or
i t.
B U IL D ER B EN EF IT S

Encapsulates the way a complex object is constructed.

Allows objects to be constructed in a multistep and varying


process (as opposed to one-step factories).

Hides the internal representation of the product from the client.

Product implementations can be swapped in and out because


the client only sees an abstract interface.

B U IL D ER U SES AN D D R AW B AC K S

Often used for building composite structures.

Constructing objects requires more domain knowledge of the


client than when using a Factory.

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.

A l l f an mai l shoul d go st r ai ght t o t he CEO, al l c ompl ai nt s shoul d go


t o t he l egal depar t ment , and al l r equest s f or new mac hi nes shoul d
go t o b usi ness dev el opment . Spam shoul d b e del et ed.

Your task

Mi ght y Gumb al l has al r eady w r i t t en some A I det ec t or s t hat c an


t el l i f an emai l i s spam, f an mai l , a c ompl ai nt , or a r equest , b ut t hey
need y ou t o c r eat e a desi gn t hat c an use t he det ec t or s t o handl e
i nc omi ng emai l .
How to use the Chain of Responsibility Pattern
W i t h t he Chai n of Responsi b i l i t y Pat t er n, y ou c r eat e a c hai n of
ob jec t s t o ex ami ne r equest s. Eac h ob jec t i n t ur n ex ami nes a r equest
and ei t her handl es i t or passes i t on t o t he nex t ob jec t i n t he c hai n.

C H AIN O F R ESPO N SIB IL IT Y B EN EF IT S

Decouples the sender of the request and its receivers.

Simplifies your object because it doesn’t have to know the


chain’s structure and keep direct references to its members.

Allows you to add or remove responsibilities dynamically by


changing the members or order of the chain.

C H AIN O F R ESPO N SIB IL IT Y U SES AN D


D R AW B AC K S

Commonly used in Windows systems to handle events like


mouse clicks and keyboard events.

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).

Can be hard to observe and debug at runtime.

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:

Your big client’s dilemma

You hav e a k ey c l i ent y ou’v e b een pi t c hi ng f or mont hs. They ’r e


goi ng t o b uy 1 ,000 seat s of y our appl i c at i on, and t hey ’r e usi ng y our
sof t w ar e t o do t he l andsc ape desi gn f or huge pl anned c ommuni t i es.
A f t er usi ng y our sof t w ar e f or a w eek , y our c l i ent i s c ompl ai ni ng
t hat w hen t hey c r eat e l ar ge gr ov es of t r ees, t he app st ar t s get t i ng
sl uggi sh...

Why use the Flyweight Pattern?


W hat i f , i nst ead of hav i ng t housands of Tr ee ob jec t s, y ou c oul d
r edesi gn y our sy st em so t hat y ou’v e got onl y one i nst anc e of Tr ee,
and a c l i ent ob jec t t hat mai nt ai ns t he st at e of A LL y our t r ees? That ’s
t he Fl y w ei ght !
F LYW EIG H T B EN EF IT S

Reduces the number of object instances at runtime, saving


memory.

Centralizes state for many “virtual” objects into a single location.

F LYW EIG H T U SES AN D D R AW B AC K S

T he Flyweight is used when a class has many instances, and


they can all be controlled identically.

A drawback of the Flyweight Pattern is that once you’ve


implemented it, single, logical instances of the class will not
be able to behave independently from the other instances.

Interpreter
Use the I nterpreter Pattern to build an interpreter for a
language.

A scenario

Rememb er t he Duc k Si mul at or ? You hav e a hunc h i t w oul d al so


mak e a gr eat educ at i onal t ool f or c hi l dr en t o l ear n pr ogr ammi ng.
U si ng t he si mul at or , eac h c hi l d get s t o c ont r ol one duc k w i t h a
si mpl e l anguage. Her e’s an ex ampl e of t he l anguage:

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.

N ow , r ememb er i ng how t o c r eat e gr ammar s f r om one of y our ol d


i nt r oduc t or y pr ogr ammi ng c l asses, y ou w r i t e out t he gr ammar :

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.

How to implement an interpreter


W hen y ou need t o i mpl ement a si mpl e l anguage, t he Int er pr et er
Pat t er n def i nes a c l ass-b ased r epr esent at i on f or i t s gr ammar al ong
w i t h an i nt er pr et er t o i nt er pr et i t s sent enc es. To r epr esent t he
l anguage, y ou use a c l ass t o r epr esent eac h r ul e i n t he l anguage.
Her e’s t he duc k l anguage t r ansl at ed i nt o c l asses. N ot i c e t he di r ec t
mappi ng t o t he gr ammar .

To i nt er pr et t he l anguage, c al l t he i nt er pr et () met hod on eac h


ex pr essi on t y pe. Thi s met hod i s passed a c ont ex t —w hi c h c ont ai ns
t he i nput st r eam of t he pr ogr am w e’r e par si ng—and mat c hes t he
i nput and ev al uat es i t .
IN T ER PR ET ER B EN EF IT S

Representing each grammar rule in a class makes the language


easy to implement.

Because the grammar is represented by classes, you can easily


change or extend the language.

By adding methods to the class structure, you can add new


behaviors beyond interpretation, like pretty printing and more
sophisticated program validation.

IN T ER PR ET ER U SES AN D D R AW B AC K S

Use Interpreter when you need to implement a simple language.

Appropriate when you have a simple grammar and simplicity is


more important than efficiency.

Used for scripting and programming languages.

T his pattern can become cumbersome when the number of


grammar rules is large. In these cases a parser/compiler
generator may be more appropriate.

Mediator
Use the Mediator Pattern to centralize complex
communications and control between related obj ects.

A scenario

Bob has an aut omat ed home, t hank s t o t he good f ol k s at


HouseOf TheFut ur e. A l l of hi s appl i anc es ar e desi gned t o mak e hi s
l i f e easi er . W hen Bob st ops hi t t i ng t he snooze b ut t on, hi s al ar m
c l oc k t el l s t he c of f ee mak er t o st ar t b r ew i ng. Ev en t hough l i f e i s
good f or Bob , he and ot her c ust omer s ar e al w ay s ask i ng f or l ot s of
new f eat ur es: N o c of f ee on t he w eek ends... Tur n of f t he spr i nk l er 1 5
mi nut es b ef or e a show er i s sc hedul ed... Set t he al ar m ear l y on t r ash
day s...

HouseOfTheFuture’s dilemma

It ’s get t i ng r eal l y har d t o k eep t r ac k of w hi c h r ul es r esi de i n


w hi c h ob jec t s, and how t he v ar i ous ob jec t s shoul d r el at e t o eac h
ot her .

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:

They t el l t he Medi at or w hen t hei r st at e c hanges.

They r espond t o r equest s f r om t he Medi at or .

Bef or e w e added t he Medi at or , al l of t he appl i anc e ob jec t s needed t o


k now ab out eac h ot her ; t hat i s, t hey w er e al l t i ght l y c oupl ed. W i t h
t he Medi at or i n pl ac e, t he appl i anc e ob jec t s ar e al l c ompl et el y
dec oupl ed f r om eac h ot her .

The Medi at or c ont ai ns al l of t he c ont r ol l ogi c f or t he ent i r e sy st em.


W hen an ex i st i ng appl i anc e needs a new r ul e, or a new appl i anc e i s
added t o t he sy st em, y ou’l l k now t hat al l of t he nec essar y l ogi c w i l l
b e added t o t he Medi at or .
M ED IAT O R B EN EF IT S

Increases the reusability of the objects supported by the


Mediator by decoupling them from the system.

Simplifies maintenance of the system by centralizing control


logic.

Simplifies and reduces the variety of messages sent between


objects in the system.

M ED IAT O R U SES AN D D R AW B AC K S

T he Mediator is commonly used to coordinate related GUI


components.

A drawback of the Mediator Pattern is that without proper design,


the Mediator object itself can become overly complex.

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

Your i nt er ac t i v e r ol e-pl ay i ng game i s hugel y suc c essf ul , and has


c r eat ed a l egi on of addi c t s, al l t r y i ng t o get t o t he f ab l ed “l ev el 1 3.”
A s user s pr ogr ess t o mor e c hal l engi ng game l ev el s, t he odds of
enc ount er i ng a game-endi ng si t uat i on i nc r ease. Fans w ho hav e
spent day s pr ogr essi ng t o an adv anc ed l ev el ar e under st andab l y
mi f f ed w hen t hei r c har ac t er get s snuf f ed, and t hey hav e t o st ar t al l
ov er . The c r y goes out f or a “sav e pr ogr ess” c ommand, so t hat
pl ay er s c an st or e t hei r game pr ogr ess and at l east r ec ov er most of
t hei r ef f or t s w hen t hei r c har ac t er i s unf ai r l y ex t i ngui shed. The
“sav e pr ogr ess” f unc t i on needs t o b e desi gned t o r et ur n a
r esur r ec t ed pl ay er t o t he l ast l ev el she c ompl et ed suc c essf ul l y .
The Memento at work
The Mement o has t w o goal s:

Sav i ng t he i mpor t ant st at e of a sy st em’s k ey ob jec t

Mai nt ai ni ng t he k ey ob jec t ’s enc apsul at i on

Keepi ng t he Si ngl e Responsi b i l i t y Pr i nc i pl e i n mi nd, i t ’s al so a


good i dea t o k eep t he st at e t hat y ou’r e sav i ng separ at e f r om t he k ey
ob jec t . Thi s separ at e ob jec t t hat hol ds t he st at e i s k now n as t he
Mement o ob jec t .

M EM EN T O B EN EF IT S

Keeping the saved state external from the key object helps to
maintain cohesion.

Keeps the key object’s data encapsulated.

Provides easy-to-implement recovery capability.

M EM EN T O U SES AN D D R AW B AC K S

T he Memento is used to save state.

A drawback to using Memento is that saving and restoring state


can be time-consuming.

In Java systems, consider using Serialization to save a


system’s state.

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.

Prototype to the rescue


The Pr ot ot y pe Pat t er n al l ow s y ou t o mak e new i nst anc es b y
c opy i ng ex i st i ng i nst anc es. (In Jav a t hi s t y pi c al l y means usi ng t he
c l one() met hod, or deser i al i zat i on w hen y ou need deep c opi es.) A
k ey aspec t of t hi s pat t er n i s t hat t he c l i ent c ode c an mak e new
i nst anc es w i t hout k now i ng w hi c h spec i f i c c l ass i s b ei ng
i nst ant i at ed.

PR O T O T YPE B EN EF IT S

Hides the complexities of making new instances from the client.

Provides the option for the client to generate objects whose type
is not known.

In some circumstances, copying an object can be more


efficient than creating a new object.

PR O T O T YPE U SES AN D D R AW B AC K S

Prototype should be considered when a system must create


new objects of many types in a complex class hierarchy.

A drawback to using Prototype is that making a copy of an


object can sometimes be complicated.

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

Cust omer s w ho f r equent t he Ob jec t v i l l e Di ner and Ob jec t v i l l e


Panc ak e House hav e r ec ent l y b ec ome mor e heal t h c onsc i ous. They
ar e ask i ng f or nut r i t i onal i nf or mat i on b ef or e or der i ng t hei r
meal s. Bec ause b ot h est ab l i shment s ar e so w i l l i ng t o c r eat e spec i al
or der s, some c ust omer s ar e ev en ask i ng f or nut r i t i onal i nf or mat i on
on a per -i ngr edi ent b asi s.

Lou’s proposed solution:


Mel’s concerns...

“Boy , i t seems l i k e w e’r e openi ng Pandor a’s b ox . W ho k now s w hat


new met hod w e’r e goi ng t o hav e t o add nex t , and ev er y t i me w e add a
new met hod w e hav e t o do i t i n t w o pl ac es. Pl us, w hat i f w e w ant t o
enhanc e t he b ase appl i c at i on w i t h, say , a r ec i pes c l ass? Then w e’l l
hav e t o mak e t hese c hanges i n t hr ee di f f er ent pl ac es...”

The Visitor drops by


The V i si t or w or k s hand i n hand w i t h a Tr av er ser . The Tr av er ser
k now s how t o nav i gat e t o al l of t he ob jec t s i n a Composi t e. The
Tr av er ser gui des t he V i si t or t hr ough t he Composi t e so t hat t he
V i si t or c an c ol l ec t st at e as i t goes. Onc e st at e has b een gat her ed, t he
Cl i ent c an hav e t he V i si t or per f or m v ar i ous oper at i ons on t he
st at e. W hen new f unc t i onal i t y i s r equi r ed, onl y t he V i si t or must b e
enhanc ed.

VISIT O R B EN EF IT S

Allows you to add operations to a Composite structure without


changing the structure itself.

Adding new operations is relatively easy.

T he code for operations performed by the Visitor is centralized.

VISIT O R D R AW B AC K S

T he Composite classes’ encapsulation is broken when the


Visitor is used.

Because the traversal function is involved, changes to the


Composite structure are more difficult.
Index

A Pat t er n Language (A l ex ander ), Your jour ney has just b egun...


ab st r ac t c l ass, Our Pi zza St or e i sn’t goi ng t o b e v er y popul ar
w i t hout some pi zzas, so l et ’s i mpl ement t hem, Templ at e Met hod
Pat t er n def i ned, Templ at e Met hod Pat t er n def i ned
A b st r ac t Fac t or y Pat t er n
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
i nt er v i ew w i t h, A b st r ac t Fac t or y Pat t er n def i ned

ab st r ac t super c l asses, Desi gni ng t he Duc k Behav i or s


A b st r ac t But t on c l ass, Look i ng f or t he Ob ser v er Pat t er n i n t he W i l d
A b st r ac t Li st , Cust om Li st s w i t h A b st r ac t Li st
A dapt er Pat t er n
ab out , The A dapt er Pat t er n ex pl ai ned
adapt i ng t o It er at or Enumer at i on i nt er f ac e, A dapt i ng an
Enumer at i on t o an It er at or
c omb i ni ng pat t er ns, Duc k r euni on
deal i ng w i t h r emov e() met hod, Deal i ng w i t h t he r emov e()
met hod
Dec or at or Pat t er n v s., W r i t i ng t he Enumer at i onIt er at or
adapt er
def i ned, A dapt er Pat t er n def i ned
desi gni ng A dapt er , A dapt i ng an Enumer at i on t o an It er at or
ex er c i ses f or , A nd now f or somet hi ng di f f er ent ..., Desi gn
Pat t er ns Cr ossw or d, Desi gn Pat t er ns Cr ossw or d, Code Magnet s
Sol ut i on, 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.
Fac ade Pat t er n v s., t her e ar e no Dumb Quest i ons
i n Model -V i ew -Cont r ol l er , A dapt i ng t he Model
ob jec t and c l ass adapt er s, Ob jec t and c l ass adapt er s
Pr ox y Pat t er n v s., t her e ar e no Dumb Quest i ons
si mpl e r eal w or l d adapt er s, Real -w or l d adapt er s
w r i t i ng Enumer at i on It er at or A dapt er , Deal i ng w i t h t he
r emov e() met hod

adapt er s, OO (Ob jec t -Or i ent ed)


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 ...
ob jec t , c l ass ob jec t and c l ass, Ob jec t and c l ass adapt er s
t est dr i v i ng, Test dr i v e t he adapt er

aggr egat es, Meet t he It er at or Pat t er n, It er at or Pat t er n def i ned


al b um c ov er s, di spl ay i ng usi ng Pr ox y Pat t er n
ab out , Di spl ay i ng A l b um c ov er s
c ode f or , The c ode f or t he A l b um Cov er V i ew er
desi gni ng V i r t ual Pr ox y , Desi gni ng t he A l b um Cov er V i r t ual
Pr ox y
r ev i ew i ng pr oc ess, W hat di d w e do?
t est i ng v i ew er , Test i ng t he A l b um Cov er V i ew er
w r i t i ng Image Pr ox y , W r i t i ng t he Image Pr ox y

A l ex ander , Chr i st opher


A Pat t er n Language, Your jour ney has just b egun...
The Ti mel ess W ay of Bui l di ng, Your jour ney has just b egun...

al gor i t hms, enc apsul at i ng


ab out , Enc apsul at i ng A l gor i t hms: The Templ at e Met hod
Pat t er n
ab st r ac t i ng pr epar eRec i pe(), A b st r ac t i ng pr epar eRec i pe()
St r at egy Pat t er n and, Speak i ng of Desi gn Pat t er ns...
Templ at e Met hod Pat t er n and
ab out , Meet t he Templ at e Met hod
appl et s i n, Cust om Li st s w i t h A b st r ac t Li st
c ode up c l ose, Templ at e Met hod Pat t er n def i ned
def i ned, Templ at e Met hod Pat t er n def i ned
hook s i n, Templ at e Met hod Pat t er n def i ned
i n r eal w or l d, Templ at e Met hods i n t he W i l d
sor t i ng w i t h, Sor t i ng w i t h Templ at e Met hod
Sw i ng and, Sw i ngi n’ w i t h Fr ames
t est i ng c ode, Let ’s r un t he Test Dr i v e
The Hol l y w ood Pr i nc i pl e and, The Hol l y w ood Pr i nc i pl e
al gor i t hms, f ami l y of , The Bi g Pi c t ur e on enc apsul at ed b ehav i or s
A nt i -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
A ppl i c ab i l i t y 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
A ppl i c at i on Pat t er ns, The Pat t er ns Zoo
A r c hi t ec t ur al Pat t er ns, The Pat t er ns Zoo
A r r ay Li st , ar r ay s and, Lou and Mel ’s Menu i mpl ement at i ons,
Br eak f ast , l unc h, A N D di nner
ar r ay s
i t er at i on and, Can w e enc apsul at e t he i t er at i on?, N ot so f ast ;
A r r ay s ar e not It er ab l es
i t er at or and hasN ex t () met hod w i t h, A ddi ng an It er at or t o
Di ner Menu
i t er at or and nex t () met hod w i t h, A ddi ng an It er at or t o
Di ner Menu

Be t he JV M sol ut i on ex er c i ses, 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
b ehav i or al pat t er ns c at egor i es, Desi gn Pat t er ns, Pat t er n
Cat egor i es, Pat t er n Cat egor i es
b ehav i or s
c l asses as, t her e ar e no Dumb Quest i ons
c l asses ex t ended t o i nc or por at e new , The Open-Cl osed
Pr i nc i pl e

dec l ar i ng v ar i ab l es, Int egr at i ng t he Duc k Behav i or s


del egat i ng t o dec or at ed ob jec t s w hi l e addi ng, Const r uc t i ng a
dr i nk or der w i t h Dec or at or s
desi gni ng, Desi gni ng t he Duc k Behav i or s
enc apsul at i ng, Desi gni ng t he Duc k Behav i or s, The Bi g Pi c t ur e
on enc apsul at ed b ehav i or s
i mpl ement i ng, Desi gni ng t he Duc k Behav i or s, Impl ement i ng
t he Duc k Behav i or s
separ at i ng, Separ at i ng w hat c hanges f r om w hat st ay s t he same
set t i ng dy nami c al l y , Set t i ng b ehav i or dy nami c al l y

Br i dge Pat t er n, Br i dge


Bui l der Pat t er n, Bui l der
Busi ness Pr oc ess Pat t er ns, The Pat t er ns Zoo

Cac hi ng Pr ox y , as f or m of V i r t ual Pr ox y , t her e ar e no Dumb


Quest i ons, The Pr ox y Zoo
Caf é Menu, i nt egr at i ng i nt o f r amew or k (It er at or Pat t er n), Tak i ng a
l ook at t he Caf é Menu
Chai n of Responsi b i l i t y Pat t er n, Chai n of Responsi b i l i t y
c hange
as t he one c onst ant i n sof t w ar e dev el opment , The one c onst ant
i n sof t w ar e dev el opment
i dent i f y i ng, The Pow er of Loose Coupl i ng
i t er at i on and, The Si ngl e Responsi b i l i t y Pr i nc i pl e

c hoc ol at e f ac t or y ex ampl e, usi ng Si ngl et on Pat t er n, The Choc ol at e


Fac t or y , Meanw hi l e, b ac k at t he Choc ol at e Fac t or y ...
c l ass adapt er s, ob jec t v s., Ob jec t and c l ass adapt er s
c l ass desi gn, of Ob ser v er Pat t er n, The Ob ser v er Pat t er n def i ned
c l ass pat t er ns, Desi gn Pat t er ns, Pat t er n Cat egor i es
c l asses, The Command Pat t er n def i ned: t he c l ass di agr am
(see al so sub c l asses)
ab st r ac t , Our Pi zza St or e i sn’t goi ng t o b e v er y popul ar w i t hout
some pi zzas, so l et ’s i mpl ement t hem, Templ at e Met hod Pat t er n
def i ned, Templ at e Met hod Pat t er n def i ned
adapt er , Her e’s how t he Cl i ent uses t he A dapt er , Desi gn
Pat t er ns Cr ossw or d
A dapt er Pat t er n, A dapt er Pat t er n def i ned
al t er i ng dec or at or , Tool s f or y our Desi gn Tool b ox
as b ehav i or s, t her e ar e no Dumb Quest i ons
c ol l ec t i on, It er at or s and Col l ec t i ons
c r eat i ng, Separ at i ng w hat c hanges f r om w hat st ay s t he same
ex t ended t o i nc or por at e new b ehav i or s, The Open-Cl osed
Pr i nc i pl e
Fac t or y Met hod Pat t er n c r eat or and pr oduc t , It ’s f i nal l y t i me
t o meet t he Fac t or y Met hod Pat t er n
hav i ng si ngl e r esponsi b i l i t y , The Si ngl e Responsi b i l i t y
Pr i nc i pl e
hi gh-l ev el c omponent , The Dependenc y Inv er si on Pr i nc i pl e
i dent i f y i ng as Pr ox y c l ass, t her e ar e no Dumb Quest i ons

r el at i onshi ps b et w een, The Bi g Pi c t ur e on enc apsul at ed


b ehav i or s
st at e
def i ni ng, Def i ni ng t he St at e i nt er f ac es and c l asses
i mpl ement i ng, Impl ement i ng our St at e c l asses,
Impl ement i ng mor e st at es, W e st i l l need t o f i ni sh t he
Gumb al l 1 i n 1 0 game
i nc r easi ng numb er i n desi gn of , t her e ar e no Dumb
Quest i ons
r ew or k i ng, Rew or k i ng t he Gumb al l Mac hi ne
st at e t r ansi t i ons i n, t her e ar e no Dumb Quest i ons

usi ng c omposi t i on w i t h, HA S-A c an b e b et t er t han IS-A


usi ng i nst anc e v ar i ab l es i nst ead of , W el c ome t o St ar b uzz
Cof f ee
usi ng i nst ead of Si ngl et ons st at i c , t her e ar e no Dumb Quest i ons
usi ng new oper at or f or i nst ant i at i ng c onc r et e, Bak i ng w i t h OO
Goodness: The Fac t or y Pat t er n

Cl assi f i c at i on 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
c l assl oader s, usi ng w i t h Si ngl et ons, t her e ar e no Dumb Quest i ons
c l i ent heap, W al k i ng t hr ough t he desi gn
c l i ent hel per (st ub s), i n RMI, Jav a RMI, t he Bi g Pi c t ur e, St ep f our :
st ar t t he ser v i c e, Compl et e c ode f or t he ser v er si de, 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 :
Code Magnet s ex er c i se
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

c ohesi on, The Si ngl e Responsi b i l i t y Pr i nc i pl e


Col l ab or at i ons 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
c ol l ec t i on c l asses, It er at or s and Col l ec t i ons
c ol l ec t i on of ob jec t s
ab st r ac t i ng w i t h It er at or Pat t er n
ab out , W el l -Managed Col l ec t i ons: The It er at or and
Composi t e Pat t er ns
addi ng It er at or s, A ddi ng an It er at or t o Di ner Menu
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
r emov e() met hod i n, Mak i ng some i mpr ov ement s...

i mpl ement i ng It er at or s f or , Meet t he It er at or Pat t er n


i nt egr at i ng i nt o f r amew or k , Tak i ng a l ook at t he Caf é Menu
meani ng of , Meet t he It er at or Pat t er n
usi ng Composi t e Pat t er n
ab out , Desi gni ng Menus w i t h Composi t e
i mpl ement i ng c omponent s, Impl ement i ng MenuComponent
t est i ng c ode, Get t i ng r eady f or a t est dr i v e...
t r ee st r uc t ur e, The Composi t e Pat t er n def i ned, Get t i ng
r eady f or a t est dr i v e...

usi ng w hol e-par t r el at i onshi ps, Get t i ng r eady f or a t est dr i v e...

Col l ec t i ons, It er at or s and, It er at or s and Col l ec t i ons


Comb i ni ng Pat t er ns
A b st r ac t Fac t or y Pat t er n, Duc k r euni on
A dapt er Pat t er n, Duc k r euni on
c l ass di agr am f or , A duc k ’s-ey e v i ew : t he c l ass di agr am
Composi t e Pat t er n, Duc k r euni on
Dec or at or Pat t er n, Duc k r euni on
It er at or Pat t er n, Duc k r euni on
Ob ser v er Pat t er n, Duc k r euni on

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

def i ned, The Command Pat t er n def i ned

dumb and smar t c ommand ob jec t s, U si ng a mac r o c ommand


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.
home aut omat i on r emot e c ont r ol
ab out , Tak i ng a l ook at t he v endor c l asses
b ui l di ng, Our f i r st c ommand ob jec t , Desi gn Pat t er ns
Cr ossw or d
c l ass di agr am, The Command Pat t er n def i ned: t he c l ass
di agr am
c r eat i ng c ommands t o b e l oaded, The Command Pat t er n
def i ned: t he c l ass di agr am
def i ni ng, The Command Pat t er n def i ned
desi gni ng, Cub i c l e Conv er sat i on
i mpl ement i ng, Impl ement i ng t he Commands
mac r o c ommands, Ev er y r emot e needs a Par t y Mode!, U si ng
a mac r o c ommand, Desi gn Pat t er ns Cr ossw or d
mappi ng, 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
N ul l Ob jec t i n, 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 ...
t est i ng, U si ng t he c ommand ob jec t , Put t i ng t he Remot e
Cont r ol t hr ough i t s pac es, U si ng a mac r o c ommand
undo c ommands, Ti me t o w r i t e t hat doc ument at i on..., Get
r eady t o t est t he c ei l i ng f an, U si ng a mac r o c ommand,
Desi gn Pat t er ns Cr ossw or d
v endor c l asses f or , Tak i ng a l ook at t he v endor c l asses
w r i t i ng doc ument at i on, Ti me t o w r i t e t hat
doc ument at i on...

l oggi ng r equest s usi ng, Mor e uses of t he Command Pat t er n:


l oggi ng r equest s
mappi ng, 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
N ul l Ob jec t , 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 ...
queui ng r equest s usi ng, Mor e uses of t he Command Pat t er n:
queui ng r equest s
under st andi ng, Meanw hi l e, b ac k at t he Di ner ..., or , A b r i ef
i nt r oduc t i on t o t he Command Pat t er n

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...

ex er c i se mat c hi ng desc r i pt i on of , Desi gn Pat t er ns Cr ossw or d,


Code Magnet s 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.
i n Model -V i ew -Cont r ol l er , U nder st andi ng MV C as a set of
Pat t er ns, t her e ar e no Dumb Quest i ons
i nt er v i ew w i t h, Get t i ng r eady f or a t est dr i v e...
on i mpl ement at i on i ssues, Get t i ng r eady f or a t est dr i v e...
saf et y v s. t r anspar enc y , Duc k r euni on
t r anspar enc y i n, Get t i ng r eady f or a t est dr i v e...
t r ee st r uc t ur e of , The Composi t e Pat t er n def i ned, 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 ompound pat t er ns, usi ng


ab out , Pat t er ns of Pat t er ns: Compound Pat t er ns
Model -V i ew -Cont r ol l er
ab out , 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..., Meet Model -V i ew -Cont r ol l er
A dapt er Pat t er n, Ex pl or i ng St r at egy
Beat model , The c ont r ol l er i s i n t he mi ddl e..., Ex er c i se
Sol ut i ons
Composi t e Pat t er n, U nder st andi ng MV C as a set of Pat t er ns,
t her e ar e no Dumb Quest i ons
c ont r ol l er s per v i ew , t her e ar e no Dumb Quest i ons
Hear t c ont r ol l er , N ow w e’r e r eady f or a Hear t Cont r ol l er ,
The Cont r ol l er
Hear t model , Ex pl or i ng St r at egy , The Hear t Model
i mpl ement i ng c ont r ol l er , N ow f or t he Cont r ol l er , The
Hear t Model
i mpl ement i ng DJ V i ew , U si ng MV C t o c ont r ol t he b eat ...,
The V i ew

Medi at or Pat t er n, t her e ar e no Dumb Quest i ons


model i n, t her e ar e no Dumb Quest i ons
Ob ser v er Pat t er n, U nder st andi ng MV C as a set of Pat t er ns,
Bui l di ng t he pi ec es
song, 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...
st at e of model , t her e ar e no Dumb Quest i ons
St r at egy Pat t er n, U nder st andi ng MV C as a set of Pat t er ns,
N ow f or t he Cont r ol l er , Ex pl or i ng St r at egy , The Hear t
Model
t est i ng, Put t i ng i t al l t oget her ...
v i ew s ac c essi ng model st at e met hods, t her e ar e no Dumb
Quest i ons

mul t i pl e pat t er ns v s., Duc k r euni on

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...

c onc r et e c r eat or s, t her e ar e no Dumb Quest i ons


c onc r et e i mpl ement at i on ob jec t , assi gni ng, Desi gni ng t he Duc k
Behav i or s
c onc r et e met hods, as hook s, Templ at e Met hod Pat t er n def i ned
c onc r et e sub c l asses, A l l ow i ng t he sub c l asses t o dec i de, A nd l et ’s
gi v e i t a r un...
Consequenc es 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
c ont r ol l i ng ob jec t ac c ess, usi ng Pr ox y Pat t er n
ab out , Cont r ol l i ng Ob jec t A c c ess: The Pr ox y Pat t er n
Cac hi ng Pr ox y , t her e ar e no Dumb Quest i ons, The Pr ox y Zoo
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
Fi r ew al l Pr ox y , The Pr ox y Zoo
Pr ot ec t i on Pr ox y
ab out , U si ng t he Jav a A PI’s Pr ox y t o c r eat e a pr ot ec t i on
pr ox y
c r eat i ng dy nami c 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
i mpl ement i ng mat c hmak i ng ser v i c e, The Per son
i mpl ement at i on
pr ot ec t i ng sub jec t s, Fi v e-mi nut e dr ama: pr ot ec t i ng
sub jec t s
t est i ng mat c hmak i ng ser v i c e, Test i ng t he mat c hmak i ng
ser v i c e
usi ng dy nami c pr ox y , U si ng t he Jav a A PI’s Pr ox y t o c r eat e
a pr ot ec t i on pr ox y

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

Smar t Ref er enc e Pr ox y , The Pr ox y Zoo


Sy nc hr oni zat i on Pr ox y , Desi gn Pat t er ns Cr ossw or d
V i r t ual Pr ox y
ab out , Get r eady f or t he V i r t ual Pr ox y

desi gni ng V i r t ual Pr ox y , Desi gni ng t he A l b um Cov er


V i r t ual Pr ox y
r ev i ew i ng pr oc ess, W hat di d w e do?
t est i ng, Test i ng t he A l b um Cov er V i ew er
w r i t i ng Image Pr ox y , W r i t i ng t he Image Pr ox y

Copy -On-W r i t e Pr ox y , Desi gn Pat t er ns Cr ossw or d


c r eat e met hod
r epl ac i ng new oper at or w i t h, Rew or k i ng t he Pi zzaSt or e c l ass
st at i c met hod v s., Bui l di ng a si mpl e pi zza f ac t or y
usi ng sub c l asses w i t h, A l l ow i ng t he sub c l asses t o dec i de

c r eat i ng st at i c c l asses i nst ead of Si ngl et on, BE t he JV M


c r eat i onal pat t er ns c at egor y , Desi gn Pat t er ns, Pat t er n Cat egor i es,
Pat t er n Cat egor i es
c r eat or c l asses, i n Fac t or y Met hod Pat t er n, It ’s f i nal l y t i me t o meet
t he Fac t or y Met hod Pat t er n, Fac t or y Met hod Pat t er n def i ned
c r ossw or d puzzl e, Desi gn Pat t er ns Cr ossw or d, Desi gn Pat t er ns
Cr ossw or d, Desi gn Pat t er ns Cr ossw or d, Desi gn Pat t er ns Cr ossw or d,
Desi gn Pat t er ns Cr ossw or d, Desi gn Pat t er ns Cr ossw or d, Cust om
Li st s w i t h A b st r ac t Li st , Desi gn Pat t er ns Cr ossw or d, Desi gn Pat t er ns
Cr ossw or d
Cunni ngham, W ar d, Ot her Desi gn Pat t er ns r esour c es

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

ex er c i ses f or , A nd now f or somet hi ng di f f er ent ..., Desi gn


Pat t er ns Cr ossw or d, 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.
i n Jav a I/O, Real -W or l d Dec or at or s: Jav a I/O
i n St r uc t ur al pat t er ns c at egor y , Pat t er n Cat egor i es
i nt er v i ew w i t h, Test out y our new Jav a I/O Dec or at or
Pr ox y Pat t er n v s., t her e ar e no Dumb Quest i ons
St ar b uzz Cof f ee pr ojec t
ab out , W el c ome t o St ar b uzz Cof f ee
addi ng si zes t o c ode, t her e ar e no Dumb Quest i ons
c onst r uc t i ng dr i nk or der s, Const r uc t i ng a dr i nk or der w i t h
Dec or at or s
dr aw i ng b ev er age or der pr oc ess, N ew b ar i st a t r ai ni ng,
Tool s f or y our Desi gn Tool b ox
t est i ng or der c ode, Ser v i ng some c of f ees
w r i t i ng c ode, W r i t i ng t he St ar b uzz c ode

dec oupl i ng, It er at or al l ow 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
del egat 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
depend upon ab st r ac t i ons desi gn pr i nc i pl e, The Dependenc y
Inv er si on Pr i nc i pl e
dependenc e, i n Ob ser v er Pat t er n, The Ob ser v er Pat t er n: t he Cl ass
Di agr am
Dependenc y Inv er si on Pr i nc i pl e (DIP), The Dependenc y Inv er si on
Pr i nc i pl e, t her e ar e no Dumb Quest i ons
dependenc y r ot , The Hol l y w ood Pr i nc i pl e
Desi gn Pat t er ns
b ec omi ng w r i t er of , So y ou w anna b e a Desi gn Pat t er ns w r i t er
b ehav i or al pat t er ns c at egor y , Pat t er n Cat egor i es, Pat t er n
Cat egor i es
c at egor i es of , Pat t er n Cat egor i es
c l ass pat t er ns, Pat t er n Cat egor i es
c r eat i onal pat t er ns c at egor y , Pat t er n Cat egor i es, Pat t er n
Cat egor i es
def i ned, Desi gn Pat t er n def i ned
di sc ov er i ng ow n, 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 , Boy , i t ’s b een gr eat hav i ng
y ou i n Ob jec t v i l l e.
f r amew or k s v s., How do I use Desi gn Pat t er ns?
gui de t o b et t er l i v i ng w i t h, Pat t er ns i n t he Real W or l d: Bet t er
Li v i ng w i t h Pat t er ns
i mpl ement on i nt er f ac e i n, The Si mpl e Fac t or y def i ned
l i b r ar i es v s., How do I use Desi gn Pat t er ns?
ob jec t pat t er ns, Pat t er n Cat egor i es
or gani zi ng, Or gani zi ng Desi gn Pat t er ns
ov er usi ng, Your Mi nd on Pat t er ns
r esour c es f or , Your jour ney has just b egun...
r ul e of t hr ee appl i ed t o, So y ou w anna b e a Desi gn Pat t er ns
w r i t er
st r uc t ur al pat t er ns c at egor y , Pat t er n Cat egor i es, Pat t er n
Cat egor i es
t hi nk i ng i n pat t er ns, Thi nk i ng i n Pat t er ns
usi ng, How do I use Desi gn Pat t er ns?, If y ou don’t need i t now ,
don’t do i t now ., Your Mi nd on Pat t er ns
y our mi nd on pat t er ns, Your Mi nd on Pat t er ns

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

dr aw i ng par al l el set of c l asses, Desi gn Puzzl e, Desi gn Puzzl e


Sol ut i on
dr aw i ng st at e di agr am, Desi gn Puzzl e, Desi gn Puzzl e Sol ut i on
of c l asses and i nt er f ac es, Desi gn Puzzl e, Desi gn Puzzl e Sol ut i on
r edesi gni ng c l asses t o r emov e r edundanc y , It ’s t i me f or some
mor e c af f ei ne, A nd now t he Tea...
r edesi gni ng Image Pr ox y , W r i t i ng t he Image Pr ox y , Tool s f or
y our Desi gn Tool b ox

desser t sub menu, usi ng Composi t e Pat t er n


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...
di ner menus, mer gi ng (It er at or Pat t er n)
ab out , Br eak i ng N ew s: Ob jec t v i l l e Di ner and Ob jec t v i l l e
Panc ak e House Mer ge
addi ng It er at or s, A ddi ng an It er at or t o Di ner Menu
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
enc apsul at i ng It er at or , Can w e enc apsul at e t he i t er at i on?
i mpl ement i ng It er at or s f or , Meet t he It er at or Pat t er n
i mpl ement i ng of , Lou and Mel ’s Menu i mpl ement at i ons

DIP (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, t her e ar e no Dumb Quest i ons
DJ V i ew , U si ng MV C t o c ont r ol t he b eat ..., Ex er c i se Sol ut i ons
Domai n-Spec i f i c Pat t er ns, The Pat t er ns Zoo
doub l e-c hec k ed l oc k i ng, r educ i ng use of sy nc hr oni zat i on usi ng, 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().
Duc k Magnet s ex er c i ses, ob jec t and c l ass ob jec t and c l ass adapt er s,
Duc k Magnet s
duc k si mul at or , r eb ui l di ng
ab out , Duc k r euni on
addi ng A b st r ac t Fac t or y Pat t er n, Duc k r euni on, Ex er c i se
Sol ut i ons
addi ng A dapt er Pat t er n, Duc k r euni on
addi ng Composi t e Pat t er n, Duc k r euni on
addi ng Dec or at or Pat t er n, Duc k r euni on
addi ng It er at or Pat t er n, Duc k r euni on
addi ng Ob ser v er Pat t er n, Duc k r euni on
c l ass di agr am, A duc k ’s-ey e v i ew : t he c l ass di agr am

dumb c ommand ob jec t s, U si ng a mac r o c ommand


dy nami c aspec t of dy nami c pr ox i es, t her e ar e no Dumb Quest i ons
dy nami c pr ox y , U si ng t he Jav a A PI’s Pr ox y t o c r eat e a pr ot ec t i on
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

Enc apsul at e w hat v ar i es desi gn pr i nc i pl e, 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...
enc apsul at i ng
b ehav i or , Desi gni ng t he Duc k Behav i or s
c ode, The Bi g Pi c t ur e on enc apsul at ed b ehav i or s,
Enc apsul at i ng ob jec t c r eat i on, t her e ar e no Dumb Quest i ons
i t er at i on, Can w e enc apsul at e t he i t er at i on?
met hod i nv oc at i on, Enc apsul at i ng Inv oc at i on: The Command
Pat t er n, The Command Pat t er n def i ned
ob jec t c onst r uc t i on, Bui l der
r equest s, The Command Pat t er n def i ned

enc apsul at i ng al gor i t hms


ab out , Enc apsul at i ng A l gor i t hms: The Templ at e Met hod
Pat t er n
ab st r ac t i ng pr epar eRec i pe(), A b st r ac t i ng pr epar eRec i pe()
Templ at e Met hod Pat t er n and
ab out , Meet t he Templ at e Met hod
A b st r ac t Li st and, Cust om Li st s w i t h A b st r ac t Li st
c ode up c l ose, Templ at e Met hod Pat t er n def i ned
def i ned, Templ at e Met hod Pat t er n def i ned
hook s i n, Templ at e Met hod Pat t er n def i ned
i n r eal w or l d, Templ at e Met hods i n t he W i l d
sor t i ng w i t h, Sor t i ng w i t h Templ at e Met hod
Sw i ng and, Sw i ngi n’ w i t h Fr ames
t est i ng c ode, Let ’s r un t he Test Dr i v e
The Hol l y w ood Pr i nc i pl e and, The Hol l y w ood Pr i nc i pl e

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

deal i ng w i t h mul t i t hr eadi ng, Duc k Magnet s


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
dr aw i ng par al l el set of c l asses, Desi gn Puzzl e, Desi gn
Puzzl e Sol ut i on
dr aw i ng st at e di agr am, Desi gn Puzzl e, Desi gn Puzzl e
Sol ut i on
of c l asses and i nt er f ac es, Desi gn Puzzl e, Desi gn Puzzl e
Sol ut i on
r edesi gni ng c l asses t o r emov e r edundanc y , A nd now t he
Tea...
r edesi gni ng Image Pr ox y , W r i t i ng t he Image Pr ox y , Tool s
f or y our Desi gn Tool b ox

Duc k Magnet s ex er c i ses, ob jec t and c l ass ob jec t and c l ass


adapt er s, Duc k Magnet s
i mpl ement i ng It er at or , Rew or k i ng t he Di ner Menu w i t h
It er at or
i mpl ement i ng undo b ut t on f or mac r o c ommand, U si ng a mac r o
c ommand, Desi gn Pat t er ns Cr ossw or d
Shar pen Your Penc i l
al t er i ng dec or at or c l asses, t her e ar e no Dumb Quest i ons,
Tool s f or y our Desi gn Tool b ox
annot at i ng Gumb al l Mac hi ne st at es, Let ’s t ak e a l ook at
w hat w e’v e done so f ar ..., Desi gn Puzzl e Sol ut i on
annot at i ng st at e di agr am, Def i ni ng t he St at e i nt er f ac es and
c l asses, Desi gn Puzzl e Sol ut i on
b ui l di ng i ngr edi ent f ac t or y , Bui l di ng t he N ew Yor k
i ngr edi ent f ac t or y , Desi gn Puzzl e Sol ut i on
c hangi ng c l asses f or Dec or at or Pat t er n, Duc k r euni on,
Ex er c i se Sol ut i ons
c hangi ng c ode t o f i t f r amew or k i n It er at or Pat t er n, Tak i ng
a l ook at t he Caf é Menu, Tool s f or y our Desi gn Tool b ox
c hoosi ng desc r i pt i ons of st at e of i mpl ement at i on, The
messy STA TE of t hi ngs..., Desi gn Puzzl e Sol ut i on
c l ass di agr am f or i mpl ement at i on of pr epar eRec i pe(),
A b st r ac t i ng pr epar eRec i pe(), Tool s f or y our Desi gn
Tool b ox
c ode not usi ng f ac t or i es, t her e ar e no Dumb Quest i ons,
Desi gn Puzzl e Sol ut i on
c r eat i ng c ommands f or of f b ut t ons, U si ng a mac r o
c ommand, Desi gn Pat t er ns Cr ossw or d
c r eat i ng heat i ndex , Pow er up t he W eat her St at i on
det er mi ni ng c l asses v i ol at i ng Pr i nc i pl e of Least
Know l edge, t her e ar e no Dumb Quest i ons, Desi gn Pat t er ns
Cr ossw or d
dr aw i ng b ev er age or der pr oc ess, Tool s f or y our Desi gn
Tool b ox
f i x i ng Choc ol at e Boi l er c ode, Meanw hi l e, b ac k at t he
Choc ol at e Fac t or y ..., Desi gn Pat t er ns Cr ossw or d

i dent i f y i ng f ac t or s i nf l uenc i ng desi gn, W el c ome t o


St ar b uzz Cof f ee
i mpl ement i ng gar age door c ommand, Cr eat i ng a si mpl e t est
t o use t he Remot e Cont r ol , Desi gn Pat t er ns Cr ossw or d
i mpl ement i ng st at e c l asses, Impl ement i ng mor e st at es,
Desi gn Puzzl e Sol ut i on
mak i ng pi zza st or e, Let ’s mak e a Pi zza St or e, Desi gn Pat t er ns
Cr ossw or d
mat c hi ng pat t er ns w i t h c at egor i es, Or gani zi ng Desi gn
Pat t er ns
met hod f or r ef i l l i ng gumb al l mac hi ne, W e al most f or got !,
Desi gn Puzzl e Sol ut i on
on addi ng b ehav i or s, t her e ar e no Dumb Quest i ons
on i mpl ement at i on of pr i nt menu(), Impl ement i ng t he spec :
our f i r st at t empt , Tool s f or y our Desi gn Tool b ox
on i nher i t anc e, Joe t hi nk s ab out i nher i t anc e..., Desi gn
Puzzl e Sol ut i on
sk et c hi ng out c l asses, The Pow er of Loose Coupl i ng
t hi ngs dr i v i ng c hange, The one c onst ant i n sof t w ar e
dev el opment , Desi gn Puzzl e Sol ut i on
t ur ni ng c l ass i nt o Si ngl et on, The Choc ol at e Fac t or y , Desi gn
Pat t er ns Cr ossw or d
w eat her st at i on SW A G, Tak i ng a f i r st , mi sgui ded
i mpl ement at i on of t he W eat her St at i on, Desi gn Pat t er ns
Cr ossw or d
w r i t i ng A b st r ac t Fac t or y Pat t er n, Duc k r euni on, Ex er c i se
Sol ut i ons
w r i t i ng c l asses f or adapt er s, Her e’s how t he Cl i ent uses t he
A dapt er , Desi gn Pat t er ns Cr ossw or d
w r i t i ng dy nami c pr ox y , St ep t w o: c r eat i ng t he Pr ox y c l ass
and i nst ant i at i ng t he Pr ox y ob jec t , Tool s f or y our Desi gn
Tool b ox
w r i t i ng Fl oc k ob ser v er c ode, Duc k r euni on, Ex er c i se
Sol ut i ons
w r i t i ng met hods f or c l asses, W el c ome t o St ar b uzz Cof f ee,
Tool s f or y our Desi gn Tool b ox

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

w r i t i ng A dapt er t hat adapt s It er at or 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
w r i t i ng handl er f or mat c hmak i ng ser v i c e, Cr eat i ng Inv oc at i on
Handl er s, c ont i nued..., Tool s f or y our Desi gn Tool b ox

ex t er nal i t er at or s, t her e ar e no Dumb Quest i ons


F

Fac ade Pat t er n


ab out , A nd now f or somet hi ng di f f er ent ...
A dapt er Pat t er n v s., t her e ar e no Dumb Quest i ons
adv ant ages, t her e ar e no Dumb Quest i ons
b enef i t s of , t her e ar e no Dumb Quest i ons
b ui l di ng home t heat er sy st em
ab out , Home Sw eet Home Theat er
c onst r uc t i ng Fac ade i n, Const r uc t i ng y our home t heat er
f ac ade

i mpl ement i ng Fac ade c l ass, Li ght s, Camer a, Fac ade!


i mpl ement i ng i nt er f ac e, Impl ement i ng t he si mpl i f i ed
i nt er f ac e

c l ass di agr am, Fac ade Pat t er n def i ned


Compl ex i t y Hi di ng Pr ox y v s., Desi gn Pat t er ns Cr ossw or d
def i ned, Fac ade Pat t er n def i ned
ex er c i ses f or , A nd now f or somet hi ng di f f er ent ..., Desi gn
Pat t er ns Cr ossw or d, Desi gn Pat t er ns Cr ossw or d, Code Magnet s
Sol ut i on, 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.
Pr i nc i pl e of Least Know l edge and, Tool s f or y our Desi gn
Tool b ox

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 Met hod Pat t er n


ab out , It ’s f i nal l y t i me t o meet t he Fac t or y Met hod Pat t er n
ab out f ac t or y ob jec t s, Enc apsul at i ng ob jec t c r eat i on
A b st r ac t Fac t or y Pat t er n and, A b st r ac t Fac t or y Pat t er n
def i ned
c ode up c l ose, Rew or k i ng t he pi zzas, c ont i nued...
c onc r et e c l asses and, Fac t or y Met hod Pat t er n def i ned
c r eat or c l asses, It ’s f i nal l y t i me t o meet t he Fac t or y Met hod
Pat t er n
dec l ar i ng f ac t or y met hod, Dec l ar i ng a f ac t or y met hod
def i ned, Fac t or y Met hod Pat t er n def i ned
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
dr aw i ng par al l el set of c l asses, Desi gn Puzzl e, Desi gn Puzzl e
Sol ut i on
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.
i nt er v i ew w i t h, A b st r ac t Fac t or y Pat t er n def i ned
l ook i ng at ob jec t dependenc i es, Look i ng at ob jec t dependenc i es
pr oduc t c l asses, It ’s f i nal l y t i me t o meet t he Fac t or y Met hod
Pat t er n
Si mpl e Fac t or y and, t her e ar e no Dumb Quest i ons

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

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, Tool s f or y our Desi gn Tool b ox
Fac t or y Met hod
ab out , It ’s f i nal l y t i me t o meet t he Fac t or y Met hod Pat t er n
adv ant ages of , t her e ar e no Dumb Quest i ons
c ode up c l ose, Rew or k i ng t he pi zzas, c ont i nued...
c r eat or c l asses, It ’s f i nal l y t i me t o meet t he Fac t or y Met hod
Pat t er n
dec l ar i ng f ac t or y met hod, Dec l ar i ng a f ac t or y met hod
def i ned, Fac t or y Met hod Pat t er n def i ned
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
dr aw i ng par al l el set of c l asses, Desi gn Puzzl e, Desi gn
Puzzl e Sol ut i on
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.
l ook i ng at ob jec t dependenc i es, Look i ng at ob jec t
dependenc i es
pr oduc t c l asses, It ’s f i nal l y t i me t o meet t he Fac t or y
Met hod Pat t er n

Si mpl e Fac t or y and, t her e ar e no Dumb Quest i ons

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

Fav or c omposi t i on ov er i nher i t anc e desi gn pr i nc i pl 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...
Fi r esi de Chat
Dec or at or Pat t er n v s. A dapt er Pat t er n, W r i t i ng t he
Enumer at i onIt er at or adapt er
St r at egy Pat t er n v s. St at e Pat t er n, Sani t y c hec k ...

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

f or c es, Look i ng mor e c l osel y at t he Desi gn Pat t er n def i ni t i on


f r amew or k s v s. l i b r ar i es, How do I use Desi gn Pat t er ns?

Gamma, Er i c h, Cr ui si n’ Ob jec t v i l l e w i t h t he Gang of Four


Gang of Four (GoF), Look i ng mor e c l osel y at t he Desi gn Pat t er n
def i ni t i on, Cr ui si n’ Ob jec t v i l l e w i t h t he Gang of Four
gl ob al ac c ess poi nt , Si ngl et on Pat t er n def i ned
gl ob al v ar i ab l es, Si ngl et on v s., t her e ar e no Dumb Quest i ons
gui de t o b et t er l i v i ng w i t h Desi gn Pat t er ns, Pat t er ns i n t he Real
W or l d: Bet t er Li v i ng w i t h Pat t er ns
gumb al l mac hi ne c ont r ol l er i mpl ement at i on, usi ng St at e Pat t er n
c l eani ng up c ode, Sani t y c hec k ...
demonst r at i on of , Demo f or t he CEO of Mi ght y Gumb al l , Inc .
di agr am t o c ode, St at e mac hi nes 1 01
f i ni shi ng, Fi ni shi ng t he game
one i n t en c ont est
ab out , You k new i t w as c omi ng...a c hange r equest !
annot at i ng st at e di agr am, Def i ni ng t he St at e i nt er f ac es and
c l asses, Desi gn Puzzl e Sol ut i on
c hangi ng c ode, The messy STA TE of t hi ngs...
dr aw i ng st at e di agr am, Desi gn Puzzl e, Desi gn Puzzl e
Sol ut i on
i mpl ement i ng st at e c l asses, Impl ement i ng our St at e
c l asses, Impl ement i ng mor e st at es, W e st i l l need t o f i ni sh
t he Gumb al l 1 i n 1 0 game
new desi gn, The new desi gn
r ew or k i ng st at e c l asses, Rew or k i ng t he Gumb al l Mac hi ne

r ef i l l i ng gumb al l mac hi ne, W e al most f or got !


Sol dSt at e and W i nner St at e i n, t her e ar e no Dumb Quest i ons
t est i ng c ode, In-house t est i ng
w r i t i ng c ode, W r i t i ng t he c ode

gumb al l mac hi ne moni t or i ng, usi ng Pr ox y Pat t er ns


ab out , Cont r ol l i ng Ob jec t A c c ess: The Pr ox y Pat t er n
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

HA S-A r el at i onshi ps, HA S-A c an b e b et t er t han IS-A , The Dec or at or


Pat t er n def i ned
HashMap, Rew or k i ng t he Caf é Menu c ode, It er at or s and Col l ec t i ons,
It er at or s and Col l ec t i ons
hasN ex t () met hod, A ddi ng an It er at or t o Di ner Menu, t her e ar e no
Dumb Quest i ons, Jav a’s enhanc ed f or l oop
Head Fi r st l ear ni ng pr i nc i pl es, A nd w e k now w hat y our b r ai n i s
t hi nk i ng.
Hel m, Ri c har d, Cr ui si n’ Ob jec t v i l l e w i t h t he Gang of Four
hi gh-l ev el c omponent c l asses, The Dependenc y Inv er si on
Pr i nc i pl e

home aut omat i on r emot e c ont r ol , usi ng Command Pat t er n


ab out , Tak i ng a l ook at t he v endor c l asses
b ui l di ng, Our f i r st c ommand ob jec t , Desi gn Pat t er ns Cr ossw or d
c l ass di agr am, The Command Pat t er n def i ned: t he c l ass di agr am
c r eat i ng c ommands t o b e l oaded, The Command Pat t er n def i ned:
t he c l ass di agr am
def i ni ng, The Command Pat t er n def i ned

desi gni ng, Cub i c l e Conv er sat i on


i mpl ement i ng, Impl ement i ng t he Commands
mac r o c ommands
ab out , Ev er y r emot e needs a Par t y Mode!
har d c odi ng v s., U si ng a mac r o c ommand
undo b ut t on, 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

mappi ng, 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
N ul l Ob jec t , 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 ...
t est i ng, U si ng t he c ommand ob jec t , Put t i ng t he Remot e Cont r ol
t hr ough i t s pac es, U si ng a mac r o c ommand
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, Desi gn Pat t er ns
Cr ossw or d
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 endor c l asses f or , Tak i ng a l ook at t he v endor c l asses


w r i t i ng doc ument at i on, Ti me t o w r i t e t hat doc ument at i on...

home t heat er sy st em, b ui l di ng


ab out , Home Sw eet Home Theat er
c onst r uc t i ng Fac ade i n, Const r uc t i ng y our home t heat er f ac ade
i mpl ement i ng i nt er f ac e, Impl ement i ng t he si mpl i f i ed
i nt er f ac e
Shar pen Your Penc i l , t her e ar e no Dumb Quest i ons
usi ng Fac ade Pat t er n, Li ght s, Camer a, Fac ade!

hook s, i n Templ at e Met hod Pat t er n, Templ at e Met hod Pat t er n


def i ned

Image Pr ox y , w r i t i ng, W r i t i ng t he Image Pr ox y


i mpl ement on i nt er f ac e, i n desi gn pat t er ns, The Si mpl e Fac t or y
def i ned
Impl ement at i on 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 mpl ement at i ons, Impl ement i ng t he Duc k Behav i or s, Mor e
i nt egr at i on..., W hat ’s w r ong w i t h our i mpl ement at i on any w ay ?
i mpor t and pac k age st at ement s, Our Pi zza St or e i sn’t goi ng t o b e
v er y popul ar w i t hout some pi zzas, so l et ’s i mpl ement t hem
i nher i t anc e
c omposi t i on v s., Cub i c l e Conv er sat i on
di sadv ant ages of , Joe t hi nk s ab out i nher i t anc e..., W el c ome t o
St ar b uzz Cof f ee
f av or i ng c omposi t i on ov er , HA S-A c an b e b et t er t han IS-A
f or mai nt enanc e, But somet hi ng w ent hor r i b l y w r ong...
f or r euse, But somet hi ng w ent hor r i b l y w r ong..., Impl ement i ng
t he Duc k Behav i or s
i mpl ement i ng mul t i pl e, Ob jec t and c l ass adapt er s

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

i nv er si on, i n Dependenc y Inv er si on Pr i nc i pl e, A ppl y i ng t he


Pr i nc i pl e
i nv ok er , Fr om t he Di ner t o t he Command Pat t er n, The Command
Pat t er n def i ned, A ssi gni ng Commands t o sl ot s, Tool s f or y our Desi gn
Tool b ox
IS-A r el at i onshi ps, HA S-A c an b e b et t er t han IS-A
It er ab l e i nt er f ac e, Meet Jav a’s It er ab l e i nt er f ac e
It er at or Pat t er n
ab out , Meet t he It er at or Pat t er n
c l ass di agr am, The It er at or Pat t er n St r uc t ur e
c ode up c l ose usi ng HashMap, Rew or k i ng t he Caf é Menu c ode
c ode v i ol at i ng 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?
Col l ec t i ons and, It er at or s and Col l ec t i ons
c omb i ni ng pat t er ns, Duc k r euni on
def i ned, It er at or Pat t er n def i ned
ex er c i se mat c hi ng desc r i pt i on of , Desi gn Pat t er ns Cr ossw or d,
Code Magnet s 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.
i nt egr at i ng Caf é Menu, Tak i ng a l ook at t he Caf é Menu
jav a.ut i l .It er at or , Mak i ng some i mpr ov ement s...
mer gi ng di ner menus
ab out , Br eak i ng N ew s: Ob jec t v i l l e Di ner and Ob jec t v i l l e
Panc ak e House Mer ge
addi ng It er at or s, A ddi ng an It er at or t o Di ner Menu
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
enc apsul at i ng It er at or , Can w e enc apsul at e t he i t er at i on?
i mpl ement i ng It er at or s f or , Meet t he It er at or Pat t er n
i mpl ement i ng of , Lou and Mel ’s Menu i mpl ement at i ons

r emov i ng ob jec t s, Mak i ng some i mpr ov ement s...


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

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

Jav a Col l ec t i ons Fr amew or k , It er at or s and Col l ec t i ons


Jav a dec or at or s (jav a.i o pac k ages), Real -W or l d Dec or at or s: Jav a I/O
Jav a Dev el opment Ki t (JDK), Look i ng f or t he Ob ser v er Pat t er n i n
t he W i l d
Jav a It er ab l e i nt er f ac e, Meet Jav a’s It er ab l e i nt er f ac e
Jav a V i r t ual Mac hi nes (JV Ms), 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()., 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
jav a.l ang.r ef l ec t pac k age, pr ox y suppor t i n, St ep f our : st ar t t he
ser v i c e, U si ng t he Jav a A PI’s Pr ox y t o c r eat e a pr ot ec t i on pr ox y ,
Cr eat i ng Inv oc at i on Handl er s, c ont i nued...
jav a.ut i l .Col l ec t i on, It er at or s and Col l ec t i ons
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
jav a.ut i l .It er at or
c l eani ng up c ode usi ng, Cl eani ng t hi ngs up w i t h
jav a.ut i l .It er at or
i nt er f ac e of , Mak i ng some i mpr ov ement s...
usi ng, t her e ar e no Dumb Quest i ons

Jav aBeans l i b r ar y , Look i ng f or t he Ob ser v er Pat t er n i n t he W i l d


JBut t on c l ass, Look i ng f or t he Ob ser v er Pat t er n i n t he W i l d
JFr ames, Sw i ng, Sw i ngi n’ w i t h Fr ames
Johnson, Ral ph, Cr ui si n’ Ob jec t v i l l e w i t h t he Gang of Four

Keep It Si mpl e (KISS), i n desi gni ng pat t er ns, Thi nk i ng i n Pat t er ns


Know n U ses 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

l amb da ex pr essi ons, Codi ng t he l i f e-c hangi ng appl i c at i on


Law of Demet er (see Pr i nc i pl e of Least Know l edge)
l azy i nst ant i at i on, Si ngl et on Pat t er n def i ned
l eav es, i n Composi t e Pat t er n t r ee st r uc t ur e, The Composi t e Pat t er n
def i ned, Get t i ng r eady f or a t est dr i v e...
l i b r ar i es, How do I use Desi gn Pat t er ns?
Li nk edLi st , It er at or s and Col l ec t i ons
Li st It t er at or , t her e ar e no Dumb Quest i ons
l oggi ng r equest s, usi ng Command Pat t er n, Mor e uses of t he
Command Pat t er n: l oggi ng r equest s
l oopi ng t hr ough ar r ay i t ems, Impl ement i ng t he spec : our f i r st
at t empt
Loose Coupl i ng Pr i nc i pl e, The Pow er of Loose Coupl i ng

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

mai nt enanc e, i nher i t anc e f or , But somet hi ng w ent hor r i b l y


w r ong...
mat c hmak i ng ser v i c e, usi ng Pr ox y Pat t er n
ab out , Geek y Mat c hmak i ng i n Ob jec t v i l l e
c r eat i ng dy nami c 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
i mpl ement i ng, The Per son i mpl ement at i on
pr ot ec t i ng sub jec t s, Fi v e-mi nut e dr ama: pr ot ec t i ng sub jec t s
t est i ng, Test i ng t he mat c hmak i ng ser v i c e

Medi at or Pat t er n, t her e ar e no Dumb Quest i ons, Medi at or


Mement o Pat t er n, Mement o
mer gi ng di ner menus (It er at or Pat t er n)
ab out , Br eak i ng N ew s: Ob jec t v i l l e Di ner and Ob jec t v i l l e
Panc ak e House Mer ge
addi ng It er at or s, A ddi ng an It er at or t o Di ner Menu
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
enc apsul at i ng It er at or , Can w e enc apsul at e t he i t er at i on?
i mpl ement i ng It er at or s f or , Meet t he It er at or Pat t er n
i mpl ement i ng of , Lou and Mel ’s Menu i mpl ement at i ons

met hod of ob jec t s, c omponent s of ob jec t v s., The Pr i nc i pl e of Least


Know l edge
met hods, 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...,
Templ at e Met hod Pat t er n def i ned
Model -V i ew -Cont r ol l er (MV C)
ab out , 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..., Meet Model -V i ew -Cont r ol l er
A dapt er Pat t er n, A dapt i ng t he Model
Beat model , The c ont r ol l er i s i n t he mi ddl e..., Ex er c i se
Sol ut i ons
Composi t e Pat t er n, U nder st andi ng MV C as a set of Pat t er ns,
t her e ar e no Dumb Quest i ons
c ont r ol l er s per v i ew , t her e ar e no Dumb Quest i ons
Hear t c ont r ol l er , N ow w e’r e r eady f or a Hear t Cont r ol l er , The
Cont r ol l er
Hear t model , Ex pl or i ng St r at egy
i mpl ement i ng c ont r ol l er , N ow f or t he Cont r ol l er , The Hear t
Model
i mpl ement i ng DJ V i ew , U si ng MV C t o c ont r ol t he b eat ..., The
V i ew
Medi at or Pat t er n, t her e ar e no Dumb Quest i ons
model i n, t her e ar e no Dumb Quest i ons
Ob ser v er Pat t er n, U nder st andi ng MV C as a set of Pat t er ns,
Bui l di ng t he pi ec es
song, 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...
st at e of model , t her e ar e no Dumb Quest i ons
St r at egy Pat t er n, U nder st andi ng MV C as a set of Pat t er ns, N ow
f or t he Cont r ol l er , Ex pl or i ng St r at egy , The Hear t Model
t est i ng, Put t i ng i t al l t oget her ...
v i ew s ac c essi ng model st at e met hods, t her e ar e no Dumb
Quest i ons

model i ng st at e, St at e mac hi nes 1 01


Mot i v at i on 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
mul t i pl e pat t er ns, usi ng
ab out , Pat t er ns of Pat t er ns: Compound Pat t er ns
i n duc k si mul at or
ab out r eb ui l di ng, Duc k r euni on
addi ng A b st r ac t Fac t or y Pat t er n, Duc k r euni on, Ex er c i se
Sol ut i ons
addi ng A dapt er Pat t er n, Duc k r euni on
addi ng Composi t e Pat t er n, Duc k r euni on
addi ng Dec or at or Pat t er n, Duc k r euni on

addi ng It er at or Pat t er n, Duc k r euni on


addi ng Ob ser v er Pat t er n, Duc k r euni on
c l ass di agr am, A duc k ’s-ey e v i ew : t he c l ass di agr am

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

N ame 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
new oper at or
r el at ed t o Si ngl et on Pat t er n, 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
r epl ac i ng w i t h c onc r et e met hod, Rew or k i ng t he Pi zzaSt or e
c l ass

nex t () met hod, A ddi ng an It er at or t o Di ner Menu, t her e ar e no Dumb


Quest i ons, Jav a’s enhanc ed f or l oop
N oCommand, i n r emot e c ont r ol c ode, 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 ...
nodes, i n Composi t e Pat t er n t r ee st r uc t ur e, The Composi t e Pat t er n
def i ned, Get t i ng r eady f or a t est dr i v e...
N ul l Ob jec t s, 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 ...

ob jec t ac c ess, usi ng Pr ox y Pat t er n f or c ont r ol l i ng


ab out , Cont r ol l i ng Ob jec t A c c ess: The Pr ox y Pat t er n
Cac hi ng Pr ox y , t her e ar e no Dumb Quest i ons, The Pr ox y Zoo
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
Fi r ew al l Pr ox y , The Pr ox y Zoo
Pr ot ec t i on Pr ox y
ab out , U si ng t he Jav a A PI’s Pr ox y t o c r eat e a pr ot ec t i on
pr ox y
c r eat i ng dy nami c 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
i mpl ement i ng mat c hmak i ng ser v i c e, The Per son
i mpl ement at i on
pr ot ec t i ng sub jec t s, Fi v e-mi nut e dr ama: pr ot ec t i ng
sub jec t s
t est i ng mat c hmak i ng ser v i c e, Test i ng t he mat c hmak i ng
ser v i c e
usi ng dy nami c pr ox y , U si ng t he Jav a A PI’s Pr ox y t o c r eat e
a pr ot ec t i on pr ox y

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

Smar t Ref er enc e Pr ox y , The Pr ox y Zoo


Sy nc hr oni zat i on Pr ox y , Desi gn Pat t er ns Cr ossw or d
V i r t ual Pr ox y
ab out , Get r eady f or t he V i r t ual Pr ox y
desi gni ng V i r t ual Pr ox y , Desi gni ng t he A l b um Cov er
V i r t ual Pr ox y
r ev i ew i ng pr oc ess, W hat di d w e do?
t est i ng, Test i ng t he A l b um Cov er V i ew er
w r i t i ng Image Pr ox y , W r i t i ng t he Image Pr ox y

ob jec t adapt er s v s. c l ass adapt er s, Ob jec t and c l ass adapt er s


ob jec t c onst r uc t i on, enc apsul at i ng, Bui l der

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

desi gn pat t er ns v s., t her e ar e no Dumb Quest i ons


ex t ensi b i l i t y and modi f i c at i on os c ode i n, t her e ar e no Dumb
Quest i ons
gui del i nes f or av oi di ng v i ol at i on of Dependenc y Inv er si on
Pr i nc i pl e, 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...
l oosel y c oupl ed desi gns and, The Pow er of Loose Coupl i ng

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

l oosel y c oupl ed desi gns b et w een, The Pow er of Loose Coupl i ng


shar i ng st at e, t her e ar e no Dumb Quest i ons
Si ngl et on, 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 , 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
w r appi ng, Meet t he Dec or at or Pat t er n, Her e’s how t he Cl i ent
uses t he A dapt er , W r i t i ng t he Enumer at i onIt er at or adapt er ,
t her e ar e no Dumb Quest i ons, Duc k r euni on
Ob ser v er Pat t er n
ab out , Keepi ng y our Ob jec t s i n t he Know : The Ob ser v er
Pat t er n, Meet t he Ob ser v er Pat t er n
c l ass pat t er ns c at egor y , So y ou w anna b e a Desi gn Pat t er ns
w r i t er
c omb i ni ng pat t er ns, Duc k r euni on
c ompar i son t o Pub l i sh-Sub sc r i b e, Pub l i sher s + Sub sc r i b er s =
Ob ser v er Pat t er n
dependenc e i n, The Ob ser v er Pat t er n: t he Cl ass Di agr am
ex ampl es of , Look i ng f or t he Ob ser v er Pat t er n i n t he W i l d
ex er c i se mat c hi ng desc r i pt i on of , Desi gn Pat t er ns Cr ossw or d,
Code Magnet s Sol ut i on, Boy , i t ’s b een gr eat hav i ng y ou i n
Ob jec t v i l l e.
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 Model -V i ew -Cont r ol l er , U nder st andi ng MV C as a set of
Pat t er ns, Bui l di ng t he pi ec es
l oose c oupl i ng i n, The Pow er of Loose Coupl i ng
Ob ser v er ob jec t i n, Pub l i sher s + Sub sc r i b er s = Ob ser v er
Pat t er n
one-t o-many r el at i onshi ps, The Ob ser v er Pat t er n def i ned
pr oc ess, A day i n t he l i f e of t he Ob ser v er Pat t er n
Sub jec t ob jec t i n, Pub l i sher s + Sub sc r i b er s = Ob ser v er Pat t er n
w eat her st at i on usi ng
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
SW A G, Tak i ng a f i r st , mi sgui ded i mpl ement at i on of t he
W eat her St at i on

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

OCP (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...
One Cl ass, One Responsi b i l i t y Pr i nc i pl e (see Si ngl e Responsi b i l i t y
Pr i nc i pl e (SRP))
one i n t en c ont est i n gumb al l mac hi ne, usi ng St at e Pat t er n
ab out , You k new i t w as c omi ng...a c hange r equest !
annot at i ng st at e di agr am, Def i ni ng t he St at e i nt er f ac es and
c l asses, Desi gn Puzzl e Sol ut i on
c hangi ng c ode, The messy STA TE of t hi ngs...

dr aw i ng st at e di agr am, Desi gn Puzzl e, Desi gn Puzzl e Sol ut i on


i mpl ement i ng st at e c l asses, Impl ement i ng our St at e c l asses,
Impl ement i ng mor e st at es, W e st i l l need t o f i ni sh t he Gumb al l
1 i n 1 0 game
new desi gn, The new desi gn
r ew or k i ng st at e c l asses, Rew or k i ng t he Gumb al l Mac hi ne

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

pac k age and i mpor t st at ement s, Our Pi zza St or e i sn’t goi ng t o b e


v er y popul ar w i t hout some pi zzas, so l et ’s i mpl ement t hem
par t -w hol e hi er ar c hy , The Composi t e Pat t er n def i ned
Par t i c i pant s 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
pat t er n c at al ogs, Look i ng mor e c l osel y at t he Desi gn Pat t er n
def i ni t i on, Look i ng mor e c l osel y at t he Desi gn Pat t er n def i ni t i on
Pat t er n Deat h Mat c h pages, Pat t er ns of Pat t er ns: Compound
Pat t er ns
pat t er n t empl at es, uses of , So y ou w anna b e a Desi gn Pat t er ns
w r i t er
pat t er ns, usi ng c ompound, Pat t er ns of Pat t er ns: Compound Pat t er ns
pat t er ns, usi ng mul t i pl e
ab out , Pat t er ns of Pat t er ns: Compound Pat t er ns
i n duc k si mul at or
ab out r eb ui l di ng, Duc k r euni on
addi ng A b st r ac t Fac t or y Pat t er n, Duc k r euni on, Ex er c i se
Sol ut i ons
addi ng A dapt er Pat t er n, Duc k r euni on
addi ng Composi t e Pat t er n, Duc k r euni on
addi ng Dec or at or Pat t er n, Duc k r euni on
addi ng It er at or Pat t er n, Duc k r euni on
addi ng Ob ser v er Pat t er n, Duc k r euni on
c l ass di agr am, A duc k ’s-ey e v i ew : t he c l ass di agr am

Pi zza St or e pr ojec t , usi ng Fac t or y Pat t er n


A b st r ac t Fac t or y i n, W hat hav e w e done?, A b st r ac t Fac t or y
Pat t er n def i ned
b ehi nd t he sc enes, Et han and Joel c an’t get enough Ob jec t v i l l e
Pi zza! W hat t hey don’t k now i s t hat now t hei r or der s ar e
mak i ng use of t he new i ngr edi ent f ac t or i es. So now w hen t hey
or der ...
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
c onc r et e sub c l asses i n, A l l ow i ng t he sub c l asses t o dec i de
dr aw i ng par al l el set of c l asses, Desi gn Puzzl e, Desi gn Puzzl e
Sol ut i on
enc apsul at i ng ob jec t c r eat i on, Enc apsul at i ng ob jec t c r eat i on
ensur i ng c onsi st enc y i n i ngr edi ent s, Meanw hi l e, b ac k at t he
Pi zza St or e..., Desi gn Puzzl e Sol ut i on
f r amew or k f or , A f r amew or k f or t he pi zza st or e
f r anc hi si ng st or e, Fr anc hi si ng t he pi zza st or e

i dent i f y i ng aspec t s i n, Ident i f y i ng t he aspec t s t hat v ar y


i mpl ement i ng, Inv er t i ng y our t hi nk i ng...
mak i ng pi zza st or e i n, Let ’s mak e a Pi zza St or e
or der i ng pi zza, Our Pi zza St or e i sn’t goi ng t o b e v er y popul ar
w i t hout some pi zzas, so l et ’s i mpl ement t hem
r ef er enc i ng l oc al i ngr edi ent f ac t or i es, Rev i si t i ng our pi zza
st or es
r ew or k i ng pi zzas, Rew or k i ng t he pi zzas...

pol y mor phi c c ode, usi ng on i t er at or , It er at or Pat t er n def i ned,


t her e ar e no Dumb Quest i ons
pol y mor phi sm, Desi gni ng t he Duc k Behav i or s
pr epar eRec i pe(), ab st r ac t i ng, A b st r ac t i ng pr epar eRec i pe()
Pr i nc i pl e of Least Know l edge, The Pr i nc i pl e of Least Know l edge
(see al so Si ngl e Responsi b i l i t y Pr i nc i pl e (SRP))

pr i nt () met hod, i n desser t sub menu usi ng Composi t e Pat t er n,


Impl ement i ng MenuComponent
Pr ogr am t o an i nt er f ac e, not an i mpl ement at i on desi gn pr i nc i pl e,
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?
pr ogr am t o i nt er f ac e v s. pr ogr am t o super t y pe, Desi gni ng t he Duc k
Behav i or s
pr ogr ammi ng, Desi gni ng t he Duc k Behav i or s
Pr ot ec t i on Pr ox y
ab out , U si ng t he Jav a A PI’s Pr ox y t o c r eat e a pr ot ec t i on pr ox y
c r eat i ng dy nami c 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
i mpl ement i ng mat c hmak i ng ser v i c e, The Per son
i mpl ement at i on
pr ot ec t i ng sub jec t s, Fi v e-mi nut e dr ama: pr ot ec t i ng sub jec t s
Pr ox y Pat t er n and, t her e ar e no Dumb Quest i ons
t est i ng mat c hmak i ng ser v i c e, Test i ng t he mat c hmak i ng
ser v i c e
usi ng dy nami c pr ox y , U si ng t he Jav a A PI’s Pr ox y t o c r eat e a
pr ot ec t i on pr ox y

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

jav a.l ang.r ef l ec t pac k age, St ep f our : st ar t t he ser v i c e, U si ng


t he Jav a A PI’s Pr ox y t o c r eat e a pr ot ec t i on pr ox y , Cr eat i ng
Inv oc at i on Handl er s, c ont i nued...
Pr ot ec t i on Pr ox y and
ab out , U si ng t he Jav a A PI’s Pr ox y t o c r eat e a pr ot ec t i on
pr ox y
A dapt er s and, t her e ar e no Dumb Quest i ons
c r eat i ng dy nami c 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
i mpl ement i ng mat c hmak i ng ser v i c e, The Per son
i mpl ement at i on
pr ot ec t i ng sub jec t s, Fi v e-mi nut e dr ama: pr ot ec t i ng
sub jec t s
t est i ng mat c hmak i ng ser v i c e, Test i ng t he mat c hmak i ng
ser v i c e
usi ng dy nami c pr ox y , U si ng t he Jav a A PI’s Pr ox y t o c r eat e
a pr ot ec t i on pr ox y

Real Sub jec t


as sur r ogat e of , t her e ar e no Dumb Quest i ons
i nv ok i ng met hod on, St ep one: c r eat i ng Inv oc at i on
Handl er s
mak i ng c l i ent use Pr ox y i nst ead of , t her e ar e no Dumb
Quest i ons

passi ng i n c onst r uc t or , Cr eat i ng Inv oc at i on Handl er s,


c ont i nued...
r et ur ni ng pr ox y f or , St ep t w o: c r eat i ng t he Pr ox y c l ass and
i nst ant i at i ng t he Pr ox y ob jec t

r est r i c t i ons on passi ng t y pes of i nt er f ac es, t her e ar e no Dumb


Quest i ons
Smar t Ref er enc e Pr ox y , The Pr ox y Zoo
Sy nc hr oni zat i on Pr ox y , Desi gn Pat t er ns Cr ossw or d
v ar i at i ons, t her e ar e no Dumb Quest i ons, The Pr ox y Zoo
V i r t ual Pr ox y
ab out , Get r eady f or t he V i r t ual Pr ox y
Cac hi ng Pr ox y as f or m of , t her e ar e no Dumb Quest i ons,
The Pr ox y Zoo
desi gni ng, Desi gni ng t he A l b um Cov er V i r t ual Pr ox y
r ev i ew i ng pr oc ess, W hat di d w e do?
t est i ng, Test i ng t he A l b um Cov er V i ew er
w r i t i ng Image Pr ox y , W r i t i ng t he Image Pr ox y

Pub l i sh-Sub sc r i b e, as 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

queui ng r equest s, usi ng Command Pat t er n, Mor e uses of t he


Command Pat t er n: queui ng r equest s

Real Sub jec t


as sur r ogat e of Pr ox y Pat t er n, t her e ar e no Dumb Quest i ons
i nv ok i ng met hod on, St ep one: c r eat i ng Inv oc at i on Handl er s
mak i ng c l i ent use pr ox y i nst ead of , t her e ar e no Dumb
Quest i ons
passi ng i n c onst r uc t or , Cr eat i ng Inv oc at i on Handl er s,
c ont i nued...
r et ur ni ng pr ox y f or , St ep t w o: c r eat i ng t he Pr ox y c l ass and
i nst ant i at i ng t he Pr ox y ob jec t

r ef ac t or i ng, W hat do w e need?, You k now y ou need a pat t er n w hen...


Rel at ed pat t er ns 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
r el at i onshi ps, b et w een c l asses, The Bi g Pi c t ur e on enc apsul at ed
b ehav i or s
Remot e Met hod Inv oc at i on (RMI)
ab out , 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, Jav a RMI, t he Bi g Pi c t ur e

c ode up c l ose, Compl et e c ode f or t he ser v er si de


c ompl et i ng c ode f or ser v er si de, Compl et e c ode f or t he ser v er
si de
i mpor t i ng jav a.r mi , 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
i mpor t i ng pac k ages, 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, N ow f or t he Gumb al l Moni t or c l i ent ...
mak i ng r emot e ser v i c e, Mak i ng t he Remot e ser v i c e
met hod c al l i n, How t he met hod c al l happens
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 ...
t hi ngs t o w at c h out f or i n, Compl et e c ode f or t he c l i ent si de

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

r emov e() met hod


Enumer at i on and, Deal i ng w i t h t he r emov e() met hod
i n c ol l ec t i on of ob jec t s, Mak i ng some i mpr ov ement s...
i n jav a.ut i l .It er at or , t her e ar e no Dumb Quest i ons

r equest s, enc apsul at i ng, The Command Pat t er n def i ned


r esour c es, Desi gn Pat t er ns, Your jour ney has just b egun...
r euse, But somet hi ng w ent hor r i b l y w r ong..., W el c ome t o St ar b uzz
Cof f ee
r ul e of t hr ee, appl i ed t o i nv ent i ng Desi gn Pat t er ns, So y ou w anna
b e a Desi gn Pat t er ns w r i t er
r unt i me er r or s, c auses of , t her e ar e no Dumb Quest i ons

Sampl e c ode 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
ser v er heap, W al k i ng t hr ough t he desi gn
ser v i c e hel per (sk el et ons), i n RMI, Jav a RMI, t he Bi g Pi c t ur e, St ep
f our : st ar t t he ser v i c e, Compl et e c ode f or t he ser v er si de, 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 :
shar ed v oc ab ul ar y , Ov er hear d at t he l oc al di ner ..., The pow er of a
shar ed pat t er n v oc ab ul ar y , You k now y ou need a pat t er n w hen...
Shar pen Your Penc i l
al t er i ng dec or at or c l asses, t her e ar e no Dumb Quest i ons, Tool s
f or y our Desi gn Tool b ox
annot at i ng Gumb al l Mac hi ne St at es, Let ’s t ak e a l ook at w hat
w e’v e done so f ar ..., Desi gn Puzzl e Sol ut i on
annot at i ng st at e di agr am, Def i ni ng t he St at e i nt er f ac es and
c l asses, Desi gn Puzzl e Sol ut i on
b ui l di ng i ngr edi ent f ac t or y , Bui l di ng t he N ew Yor k i ngr edi ent
f ac t or y , Desi gn Puzzl e Sol ut i on
c hangi ng c l asses f or Dec or at or Pat t er n, Duc k r euni on,
Ex er c i se Sol ut i ons
c hangi ng c ode t o f i t f r amew or k i n It er at or Pat t er n, Tak i ng a
l ook at t he Caf é Menu, Tool s f or y our Desi gn Tool b ox
c hoosi ng desc r i pt i ons of st at e of i mpl ement at i on, The messy
STA TE of t hi ngs..., Desi gn Puzzl e Sol ut i on
c l ass di agr am f or i mpl ement at i on of pr epar eRec i pe(),
A b st r ac t i ng pr epar eRec i pe(), Tool s f or y our Desi gn Tool b ox
c ode not usi ng f ac t or i es, t her e ar e no Dumb Quest i ons, Desi gn
Puzzl e Sol ut i on
c r eat i ng c ommands f or of f b ut t ons, U si ng a mac r o c ommand,
Desi gn Pat t er ns Cr ossw or d
c r eat i ng heat i ndex , Pow er up t he W eat her St at i on
det er mi ni ng c l asses v i ol at i ng Pr i nc i pl e of Least Know l edge,
t her e ar e no Dumb Quest i ons, Desi gn Pat t er ns Cr ossw or d
dr aw i ng b ev er age or der pr oc ess, Tool s f or y our Desi gn Tool b ox
f i x i ng Choc ol at e Boi l er c ode, Meanw hi l e, b ac k at t he Choc ol at e
Fac t or y ..., Desi gn Pat t er ns Cr ossw or d
i dent i f y i ng f ac t or s i nf l uenc i ng desi gn, W el c ome t o St ar b uzz
Cof f ee
i mpl ement i ng gar age door c ommand, Cr eat i ng a si mpl e t est t o
use t he Remot e Cont r ol , Desi gn Pat t er ns Cr ossw or d
i mpl ement i ng st at e c l asses, Impl ement i ng mor e st at es, Desi gn
Puzzl e Sol ut i on

mak i ng pi zza st or e, Let ’s mak e a Pi zza St or e, Desi gn Pat t er ns


Cr ossw or d
mat c hi ng pat t er ns w i t h c at egor i es, Or gani zi ng Desi gn Pat t er ns
met hod f or r ef i l l i ng gumb al l mac hi ne, W e al most f or got !,
Desi gn Puzzl e Sol ut i on
on addi ng b ehav i or s, t her e ar e no Dumb Quest i ons
on i mpl ement at i on of pr i nt menu(), Impl ement i ng t he spec : our
f i r st at t empt , Tool s f or y our Desi gn Tool b ox
on i nher i t anc e, Joe t hi nk s ab out i nher i t anc e..., Desi gn Puzzl e
Sol ut i on
sk et c hi ng out c l asses, The Pow er of Loose Coupl i ng
t hi ngs dr i v i ng c hange, The one c onst ant i n sof t w ar e
dev el opment , Desi gn Puzzl e Sol ut i on
t ur ni ng c l ass i nt o Si ngl et on, The Choc ol at e Fac t or y , Desi gn
Pat t er ns Cr ossw or d
w eat her st at i on SW A G, Tak i ng a f i r st , mi sgui ded
i mpl ement at i on of t he W eat her St at i on, Desi gn Pat t er ns
Cr ossw or d
w r i t i ng A b st r ac t Fac t or y Pat t er n, Duc k r euni on, Ex er c i se
Sol ut i ons
w r i t i ng c l asses f or adapt er s, Her e’s how t he Cl i ent uses t he
A dapt er , Desi gn Pat t er ns Cr ossw or d
w r i t i ng dy nami c pr ox y , St ep t w o: c r eat i ng t he Pr ox y c l ass and
i nst ant i at i ng t he Pr ox y ob jec t , Tool s f or y our Desi gn Tool b ox
w r i t i ng Fl oc k ob ser v er c ode, Duc k r euni on, Ex er c i se Sol ut i ons
w r i t i ng met hods f or c l asses, W el c ome t o St ar b uzz Cof f ee, Tool s
f or y our Desi gn Tool b ox

Si mpl e Fac t or y Pat t er n


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 ni t i on of , 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

Si ngl e Responsi b i l i t y Pr i nc i pl e (SRP), 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...
Si ngl et on ob jec t s, 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 , 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
Si ngl et on Pat t er n, One-of -a-Ki nd Ob jec t s: The Si ngl et on Pat t er n
ab out , One-of -a-Ki nd Ob jec t s: The Si ngl et on Pat t er n

adv ant ages of , One-of -a-Ki nd Ob jec t s: The Si ngl et on Pat t er n


Choc ol at e Fac t or y , The Choc ol at e Fac t or y , Meanw hi l e, b ac k at
t he Choc ol at e Fac t or y ...
c l ass di agr am, Si ngl et on Pat t er n def i ned
c ode up c l ose, 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
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
def i ned, Si ngl et on Pat t er n def i ned
di sadv ant ages of , t her e ar e no Dumb Quest i ons
doub l e-c hec k ed l oc k i ng, 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().
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
gl ob al v ar i ab l es v s., t her e ar e no Dumb Quest i ons
i mpl ement i ng, 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

i nt er v i ew w i t h, 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
One Cl ass, One Responsi b i l i t y Pr i nc i pl e and, t her e ar e no
Dumb Quest i ons
sub c l asses i n, t her e ar e no Dumb Quest i ons
usi ng, t her e ar e no Dumb Quest i ons

sk el et ons (ser v i c e hel per ), i n RMI, Jav a RMI, t he Bi g Pi c t ur e, St ep


f our : st ar t t he ser v i c e, Compl et e c ode f or t he ser v er si de, 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 :
smar t c ommand ob jec t s, U si ng a mac r o c ommand
Smar t Ref er enc e Pr ox y , The Pr ox y Zoo
sof t w ar e dev el opment , c hange as a c onst ant i n, The one c onst ant i n
sof t w ar e dev el opment
sor t () met hod, The mak i ng of t he sor t i ng duc k mac hi ne
sor t i ng met hods, i n Templ at e Met hod Pat t er n, Sor t i ng w i t h
Templ at e Met hod
spl i t er at or met hod, Meet Jav a’s It er ab l e i nt er f ac e
SRP (Si ngl e 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...
St ar b uzz Cof f ee Bar i st a t r ai ni ng manual pr ojec t
ab out , It ’s t i me f or some mor e c af f ei ne
ab st r ac t i ng pr epar eRec i pe(), A b st r ac t i ng pr epar eRec i pe()
usi ng Templ at e Met hod Pat t er n
ab out , Meet t he Templ at e Met hod
c ode up c l ose, Templ at e Met hod Pat t er n def i ned
def i ned, Templ at e Met hod Pat t er n def i ned
hook s i n, Templ at e Met hod Pat t er n def i ned

t est i ng c ode, Let ’s r un t he Test Dr i v e


The Hol l y w ood Pr i nc i pl e and, The Hol l y w ood Pr i nc i pl e

St ar b uzz Cof f ee pr ojec t , usi ng Dec or at or Pat t er n


ab out , W el c ome t o St ar b uzz Cof f ee
addi ng si zes t o c ode, t her e ar e no Dumb Quest i ons
c onst r uc t i ng dr i nk or der s, Const r uc t i ng a dr i nk or der w i t h
Dec or at or s
dr aw i ng b ev er age or der pr oc ess, N ew b ar i st a t r ai ni ng, Tool s
f or y our Desi gn Tool b ox
t est i ng or der c ode, Ser v i ng some c of f ees
w r i t i ng c ode, W r i t i ng t he St ar b uzz c ode

st at e mac hi nes, St at e mac hi nes 1 01


St at e Pat t er n
def i ned, The St at e Pat t er n def i ned
ex er c i se mat c hi ng desc r i pt i on of , W e al most f or got !, Desi gn
Puzzl e 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.
gumb al l mac hi ne c ont r ol l er i mpl ement at i on
c l eani ng up c ode, Sani t y c hec k ...
demonst r at i on of , Demo f or t he CEO of Mi ght y Gumb al l ,
Inc .

di agr am t o c ode, St at e mac hi nes 1 01


f i ni shi ng, Fi ni shi ng t he game
r ef i l l i ng gumb al l mac hi ne, W e al most f or got !
Sol dSt at e and W i nner St at e i n, t her e ar e no Dumb Quest i ons
t est i ng c ode, In-house t est i ng
w r i t i ng c ode, W r i t i ng t he c ode

i nc r easi ng numb er of c l asses i n desi gn, t her e ar e no Dumb


Quest i ons

model i ng st at e, St at e mac hi nes 1 01


one i n t en c ont est i n gumb al l mac hi ne
ab out , You k new i t w as c omi ng...a c hange r equest !
annot at i ng st at e di agr am, Def i ni ng t he St at e i nt er f ac es and
c l asses, Desi gn Puzzl e Sol ut i on
c hangi ng c ode, The messy STA TE of t hi ngs...
dr aw i ng st at e di agr am, Desi gn Puzzl e, Desi gn Puzzl e
Sol ut i on

i mpl ement i ng st at e c l asses, Impl ement i ng our St at e


c l asses, Impl ement i ng mor e st at es, W e st i l l need t o f i ni sh
t he Gumb al l 1 i n 1 0 game
new desi gn, The new desi gn
r ew or k i ng st at e c l asses, Rew or k i ng t he Gumb al l Mac hi ne

shar i ng st at e ob jec t s, t her e ar e no Dumb Quest i ons


st at e t r ansi t i ons i n st at e c l asses, t her e ar e no Dumb Quest i ons
St r at egy Pat t er n v s., The St at e of Thi ngs: The St at e Pat t er n, The
St at e Pat t er n def i ned, Sani t y c hec k ...
st at e t r ansi t i ons, i n st at e c l asses, t her e ar e no Dumb Quest i ons
st at e, usi ng t o i mpl ement undo c ommands, U si ng st at e t o i mpl ement
U ndo
st at i c c l asses, usi ng i nst ead of Si ngl et ons, t her e ar e no Dumb
Quest i ons
st at i c met hod v s. c r eat e met hod, Bui l di ng a si mpl e pi zza f ac t or y
St r at egy Pat t er n
al gor i t hms and, Speak i ng of Desi gn Pat t er ns...
def i ned, Speak i ng of Desi gn Pat t er ns...
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, 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, 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.
i n Model -V i ew -Cont r ol l er , U nder st andi ng MV C as a set of
Pat t er ns, N ow f or t he Cont r ol l er , Ex pl or i ng St r at egy
St at e Pat t er n v s., The St at e of Thi ngs: The St at e Pat t er n, The
St at e Pat t er n def i ned, Sani t y c hec k ...
Templ at e Met hod Pat t er n and, t her e ar e no Dumb Quest i ons

st r i v e f or l oosel y c oupl ed desi gns b et w een ob jec t s t hat i nt er ac t


desi gn pr i nc i pl e, The Pow er of Loose Coupl i ng
(see al so Loose Coupl i ng Pr i nc i pl e)

st r uc t ur al pat t er ns c at egor y , Desi gn Pat t er ns, Pat t er n Cat egor i es,


Pat t er n Cat egor i es
St r uc t ur e 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
st ub s (c l i ent hel per ), i n RMI, Jav a RMI, t he Bi g Pi c t ur e, St ep f our :
st ar t t he ser v i c e, Compl et e c ode f or t he ser v er si de, 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 :
sub c l asses, The Command Pat t er n def i ned: t he c l ass di agr am
c onc r et e c ommands and, The Command Pat t er n def i ned: t he
c l ass di agr am
c onc r et e st at es and, The St at e Pat t er n def i ned
ex pl osi on of c l asses, W el c ome t o St ar b uzz Cof f ee
Fac t or y Met hod and, l et t i ng sub c l asses dec i de w hi c h c l ass t o
i nst ant i at e, Fac t or y Met hod Pat t er n def i ned
i n Si ngl et ons, t her e ar e no Dumb Quest i ons
Pi zza St or e c onc r et e, A l l ow i ng t he sub c l asses t o dec i de
Templ at e Met hod, Meet t he Templ at e Met hod
t r oub l eshoot i ng, But somet hi ng w ent hor r i b l y w r ong...

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

sub sy st ems, Fac ades and, t her e ar e no Dumb Quest i ons


super c l asses, But somet hi ng w ent hor r i b l y w r ong..., Desi gni ng t he
Duc k Behav i or s
super t y pe (pr ogr ammi ng t o i nt er f ac e), v s. pr ogr ammi ng t o
i nt er f ac e, Desi gni ng t he Duc k Behav i or s
Sw i ng l i b r ar y , Look i ng f or t he Ob ser v er Pat t er n i n t he W i l d,
Sw i ngi n’ w i t h Fr ames, t her e ar e no Dumb Quest i ons
Sy nc hr oni zat i on Pr ox y , Desi gn Pat t er ns Cr ossw or d
sy nc hr oni zat i on, as ov er head, Deal i ng w i t h mul t i t hr eadi ng

Templ at e Met hod Pat t er n


ab out , Meet t he Templ at e Met hod
ab st r ac t c l ass i n, Templ at e Met hod Pat t er n def i ned, Templ at e
Met hod Pat t er n def i ned, A nd l et ’s gi v e i t a r un...
appl et s i n, Cust om Li st s w i t h A b st r ac t Li st
c l ass di agr am, Templ at e Met hod Pat t er n def i ned
c ode up c l ose, Templ at e Met hod Pat t er n def i ned
def i ned, Templ at e Met hod Pat t er n def i ned
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, Tool s f or y our Desi gn Tool b ox , W e al most f or got !,
Desi gn Puzzl e 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.
hook s i n, Templ at e Met hod Pat t er n def i ned, A nd l et ’s gi v e i t a
r un...
i n r eal w or l d, Templ at e Met hods i n t he W i l d
sor t i ng w i t h, Sor t i ng w i t h Templ at e Met hod
St r at egy Pat t er n and, t her e ar e no Dumb Quest i ons
Sw i ng and, Sw i ngi n’ w i t h Fr ames
t est i ng c ode, Let ’s r un t he Test Dr i v e
The Hol l y w ood Pr i nc i pl e and, The Hol l y w ood 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


The Ti mel ess W ay of Bui l di ng (A l ex ander ), Your jour ney has just
b egun...
t hi nk i ng i n pat t er ns, Thi nk i ng i n Pat t er ns
t i ght l y c oupl ed, The Pow er of Loose Coupl i ng
t r anspar enc y , i n Composi t e Pat t er n, Get t i ng r eady f or a t est dr i v e...
t r ee st r uc t ur e, Composi t e Pat t er n, The Composi t e Pat t er n def i ned,
Get t i ng r eady f or a t est dr i v e...
Tw o W ay A dapt er s, c r eat i ng, Her e’s how t he Cl i ent uses t he
A dapt er
t y pe saf e par amet er s, t her e ar e no Dumb Quest i ons

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

U ser Int er f ac e Desi gn Pat t er ns, The Pat t er ns Zoo

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 ec t or , It er at or s and Col l ec t i ons


V i r t ual Pr ox y
ab out , Get r eady f or t he V i r t ual Pr ox y
Cac hi ng Pr ox y as f or m of , t her e ar e no Dumb Quest i ons, The
Pr ox y Zoo
desi gni ng, Desi gni ng t he A l b um Cov er V i r t ual Pr ox y
r ev i ew i ng pr oc ess, W hat di d w e do?
t est i ng, Test i ng t he A l b um Cov er V i ew er
w r i t i ng Image Pr ox y , W r i t i ng t he Image Pr ox y

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

W ho Does W hat ex er c i ses


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

w hol e-par t r el at i onshi ps, c ol l ec t i on of ob jec t s usi ng, Get t i ng r eady


f or a t est dr i v e...
W i c k edl y smar t w eb si t e, The r edundanc y i s i nt ent i onal and
i mpor t ant .
w r appi ng ob jec t s, Meet t he Dec or at or Pat t er n, Her e’s how t he
Cl i ent uses t he A dapt er , W r i t i ng t he Enumer at i onIt er at or adapt er ,
t her e ar e no Dumb Quest i ons, t her e ar e no Dumb Quest i ons, Duc k
r euni on

y our mi nd on pat t er ns desi gn pat t er n, Your Mi nd on Pat t er ns

You might also like