You are on page 1of 46

Object-Oriented Software Engineering

Practical Software Development using UML and Java


Chapter6:
Using Design Patterns

6.1 Introduction to Patterns


Therecurringaspectsofdesignsarecalleddesignpatterns.
Apatternistheoutlineofareusablesolutiontoageneralproblem
encounteredinaparticularcontext
Many of them have been systematically documented for all
softwaredeveloperstouse
Agoodpatternshould
Beasgeneralaspossible
Containasolutionthathasbeenproventoeffectivelysolvethe
problemintheindicatedcontext.
Studyingpatternsisaneffectivewaytolearnfromtheexperienceof
others

Lethbridge/

Chapter6:Usingdesignpattern

Pattern description
Context:
Thegeneralsituationinwhichthepatternapplies
Problem:
Ashortsentenceortworaisingthemaindifficulty.
Forces:
Theissuesorconcernstoconsiderwhensolvingtheproblem
Solution:
Therecommendedwaytosolvetheprobleminthegivencontext.
tobalancetheforces

Antipatterns:(Optional)
Solutionsthatareinferiorordonotworkinthiscontext.
Relatedpatterns:(Optional)
Patternsthataresimilartothispattern.
References:
Whodevelopedorinspiredthepattern.

Lethbridge/

Chapter6:Usingdesignpattern

6.2 The Abstraction-Occurrence Pattern


Context:
Often in a domain model you find a set of related objects
(occurrences).
Themembersofsuchasetsharecommoninformation
butalsodifferfromeachotherinimportantways.

Problem:
Whatisthebestwaytorepresentsuchsetsofoccurrencesina
classdiagram?
Forces:
Youwanttorepresentthemembersofeachsetofoccurrences
withoutduplicatingthecommoninformation

Lethbridge/

Chapter6:Usingdesignpattern

Abstraction-Occurrence
Solution:

Lethbridge/

Chapter6:Usingdesignpattern

Abstraction-Occurrence
Antipatterns:

Lethbridge/

Chapter6:Usingdesignpattern

Abstraction-Occurrence
Squarevariant

Lethbridge/

Chapter6:Usingdesignpattern

6.3 The General Hierarchy Pattern


Context:
Objects in a hierarchy can have one or more objects above
them(superiors),
andoneormoreobjectsbelowthem(subordinates).

Someobjectscannothaveanysubordinates
Problem:
How do you represent a hierarchy of objects, in which some
objectscannothavesubordinates?
Forces:
Youwantaflexiblewayofrepresentingthehierarchy
thatpreventscertainobjectsfromhavingsubordinates

Alltheobjectshavemanycommonpropertiesandoperations

Lethbridge/

Chapter6:Usingdesignpattern

General Hierarchy
Solution:

Lethbridge/

Chapter6:Usingdesignpattern

General Hierarchy
Solution:

Lethbridge/

Chapter6:Usingdesignpattern

General Hierarchy
Antipattern:

Lethbridge/

Chapter6:Usingdesignpattern

6.4 The Player-Role Pattern


Context:
A role is a particular set of properties associated
withanobjectinaparticularcontext.
An object may play different roles in different
contexts.
Problem:
How do you best model players and roles so that a
playercanchangerolesorpossessmultipleroles?

Lethbridge/

Chapter6:Usingdesignpattern

Player-Role
Forces:
Itisdesirabletoimproveencapsulationbycapturingthe
informationassociatedwitheachseparateroleinaclass.
Youwanttoavoidmultipleinheritance.
Youcannotallowaninstancetochangeclass
Solution:

Lethbridge/

Chapter6:Usingdesignpattern

Player-Role
Example1:

Lethbridge/

Chapter6:Usingdesignpattern

Player-Role
Example2:

Lethbridge/

Chapter6:Usingdesignpattern

Player-Role
Antipatterns:
Merge all the properties and behaviours into a single
PlayerclassandnothaveRoleclassesatall.
CreaterolesassubclassesofthePlayerclass.

Lethbridge/

Chapter6:Usingdesignpattern

6.5 The Singleton Pattern


Context:
Itisverycommontofindclassesforwhichonlyone
instanceshouldexist(singleton)
Problem:
Howdoyouensurethatitisneverpossibletocreate
morethanoneinstanceofasingletonclass?
Forces:
Theuseofapublicconstructorcannotguaranteethat
nomorethanoneinstancewillbecreated.
Thesingletoninstancemustalsobeaccessibletoall
classesthatrequireit
Lethbridge/

Chapter6:Usingdesignpattern

Singleton
Solution:

Lethbridge/

Chapter6:Usingdesignpattern

6.6 The Observer Pattern


Context:
Whenanassociationiscreatedbetweentwoclasses,
thecodefortheclassesbecomesinseparable.
Ifyouwanttoreuseoneclass,thenyoualsohaveto
reusetheother.
Problem:
Howdoyoureducetheinterconnectionbetween
classes,especiallybetweenclassesthatbelongto
differentmodulesorsubsystems?
Forces:
Youwanttomaximizetheflexibilityofthesystem
tothegreatestextentpossible
Lethbridge/

Chapter6:Usingdesignpattern

Observer
Solution:

Lethbridge/

Chapter6:Usingdesignpattern

Observer
Antipatterns:
Connect an observer directly to an observable so that
theybothhavereferencestoeachother.
Maketheobserverssubclassesoftheobservable.

Lethbridge/

Chapter6:Usingdesignpattern

6.7 The Delegation Pattern


Context:
Youaredesigningamethodinaclass
Yourealizethatanotherclasshasamethodwhich
providestherequiredservice
Inheritanceisnotappropriate
E.g.becausetheisaruledoesnotapply

Problem:
Howcanyoumosteffectivelymakeuseofamethod
thatalreadyexistsintheotherclass?
Forces:
Youwanttominimizedevelopmentcostbyreusing
methods
Lethbridge/

Chapter6:Usingdesignpattern

Delegation
Solution:

Lethbridge/

Chapter6:Usingdesignpattern

Delegation
Example:

Lethbridge/

Chapter6:Usingdesignpattern

Delegation
Antipatterns
Overusegeneralizationandinheritthemethodthatisto
bereused
InsteadofcreatingasinglemethodintheDelegator
thatdoesnothingotherthancallamethodinthe
Delegate
considerhavingmanydifferentmethodsinthe
Delegatorcallthedelegatesmethod
Accessnonneighboringclasses

returnspecificFlight.regularFlight.flightNumber();
returngetRegularFlight().flightNumber();

Lethbridge/

Chapter6:Usingdesignpattern

6.8 The Adapter Pattern


Context:
Youarebuildinganinheritancehierarchyandwantto
incorporateitintoanexistingclass.
Thereusedclassisalsooftenalreadypartofitsowninheritance
hierarchy.
Problem:
How to obtain the power of polymorphism when reusing a
classwhosemethods
havethesamefunction
butnotthesamesignature

astheothermethodsinthehierarchy?
Forces:
You do not have access to multiple inheritance or you do not
wanttouseit.

Lethbridge/

Chapter6:Usingdesignpattern

Adapter
Solution:

Lethbridge/

Chapter6:Usingdesignpattern

Adapter
Example:

Lethbridge/

Chapter6:Usingdesignpattern

6.9 The Faade Pattern


Context:
Often,anapplicationcontainsseveralcomplexpackages.
Aprogrammerworkingwithsuchpackageshastomanipulate
manydifferentclasses
Problem:
Howdoyousimplifytheviewthatprogrammershaveofa
complexpackage?
Forces:
It is hard for a programmer to understand and use an entire
subsystem
If several different application classes call methods of the
complexpackage,thenanymodificationsmadetothepackage
willnecessitateacompletereviewofalltheseclasses.

Lethbridge/

Chapter6:Usingdesignpattern

Faade
Solution:

Lethbridge/

Chapter6:Usingdesignpattern

6.10 The Immutable Pattern


Context:
Animmutableobjectisanobjectthathasastatethatnever
changesaftercreation
Problem:
Howdoyoucreateaclasswhoseinstancesareimmutable?
Forces:
Theremustbenoloopholesthatwouldallowillegal
modificationofanimmutableobject
Solution:
Ensure that the constructor of the immutable class is the only
placewherethevaluesofinstancevariablesaresetormodified.
Instance methods which access properties must not have side
effects.
Ifamethodthatwouldotherwisemodifyaninstancevariableis
required,thenithastoreturnanewinstanceoftheclass.

Lethbridge/

Chapter6:Usingdesignpattern

6.11 The Read-only Interface Pattern


Context:
Yousometimeswantcertainprivilegedclassestobeableto
modifyattributesofobjectsthatareotherwiseimmutable
Problem:
Howdoyoucreateasituationwheresomeclassesseeaclassas
readonlywhereasothersareabletomakemodifications?
Forces:
Restrictingaccessbyusingthepublic,protectedand
privatekeywordsisnotadequatelyselective.
Makingaccesspublicmakesitpublicforbothreadingand
writing

Lethbridge/

Chapter6:Usingdesignpattern

Read-only Interface
Solution:

Lethbridge/

Chapter6:Usingdesignpattern

Read-only Interface
Example:

Lethbridge/

Chapter6:Usingdesignpattern

Read-only Interface
Antipatterns:
MakethereadonlyclassasubclassoftheMutableclass
Overrideallmethodsthatmodifyproperties
suchthattheythrowanexception

Lethbridge/

Chapter6:Usingdesignpattern

6.12 The Proxy Pattern


Context:
Often,itistimeconsumingandcomplicatedtocreateinstances
ofaclass(heavyweightclasses).
There is a time delay and a complex mechanism involved in
creatingtheobjectinmemory
Problem:
Howtoreducetheneedtocreateinstancesofaheavyweight
class?
Forces:
Wewantalltheobjectsinadomainmodeltobeavailablefor
programstousewhentheyexecuteasystemsvarious
responsibilities.
Itisalsoimportantformanyobjectstopersistfromruntorun
ofthesameprogram

Lethbridge/

Chapter6:Usingdesignpattern

Proxy
Solution:

Lethbridge/

Chapter6:Usingdesignpattern

Proxy
Examples:

Lethbridge/

Chapter6:Usingdesignpattern

6.13 The Factory Pattern


Context:
Areusableframeworkneedstocreateobjecs;howevertheclass
ofthecreatedobjectsdependsontheapplication.
Problem:
Howdoyouenableaprogrammertoaddnewapplication
specificclassintoasystembuiltonsuchaframework?
Forces:
Wewanttohavetheframeworkcreateandworkwith
applicationspecificclassesthattheframeworkdoesnotyet
knowabout.
Solution:
The framework delegates the creation of applicationspecific
classestoaspecializedclass,theFactory.
TheFactoryisagenericinterfacedefinedintheframework.
The factory interface declares a method whose purpose is to
createsomesubclassofagenericclass.

Lethbridge/

Chapter6:Usingdesignpattern

The Factory Pattern


Solution

Lethbridge/

Chapter6:Usingdesignpattern

The Factory Pattern


Example

Lethbridge/

Chapter6:Usingdesignpattern

6.14 Detailed Example: enhancing OCSF


with some design patterns

Lethbridge/

Chapter6:Usingdesignpattern

The Observable layer of OCSF (continued)

Lethbridge/

Chapter6:Usingdesignpattern

Using the observable layer


1.CreateaclassthatimplementstheObserverinterface.
2.RegisteritasanobserveroftheObservable:
public MessageHandler(Observable client)
{
client.addObserver(this);
...
}

3.Definetheupdate methodinthenewclass:
public void update(Observable obs, Object message)
{
if (message instanceOf SomeClass)
{
// process the message
}
}

Lethbridge/

Chapter6:Usingdesignpattern

6.15 Difficulties and Risks When Creating


Class Diagrams
Patternsarenotapanacea:
Wheneveryouseeanindicationthatapatternshould
beapplied,youmightbetemptedtoblindlyapplythe
pattern.
Thiscanleadtounwisedesigndecisions.
Resolution:
Alwaysunderstandindepththeforcesthatneedto
bebalanced,andwhenotherpatternsbetterbalance
theforces.
Makesureyoujustifyeachdesigndecisioncarefully.

Lethbridge/

Chapter6:Usingdesignpattern

Difficulties and Risks When Creating Class


Diagrams
Developingpatternsishard
Writingagoodpatterntakesconsiderablework.
Apoorpatterncanbehardtoapplycorrectly
Resolution:
Donotwritepatternsforotherstouseuntilyou
haveconsiderableexperiencebothinsoftware
designandintheuseofpatterns.
Takeanindepthcourseonpatterns.
Iterativelyrefineyourpatterns,andhavethempeer
reviewedateachiteration.

Lethbridge/

Chapter6:Usingdesignpattern

You might also like