patterns behavior
TRANSCRIPT
-
8/6/2019 Patterns Behavior
1/45
Design PatternsDavid Talby
-
8/6/2019 Patterns Behavior
2/45
This Lecture More fora Document Editor
SynchronizingMultiple Windows
Observer
Simplifyingcomplex interactions
Mediator
Workingoncomplexstructures
Iterator
Visitor
-
8/6/2019 Patterns Behavior
3/45
12. Observer Define a one-to-many dependency
betweenobjects,sothatchanging
one automatically updatesothers Forexample, a spreadsheet and
several chartsof it areopen
Changing data in a windowshould
be immediately reflected in all
-
8/6/2019 Patterns Behavior
4/45
The Requirements Document and Chartclassesmust
notknoweachother, forreuse
Easily add newkindsofchartsorother links
A dynamicnumberofcharts
-
8/6/2019 Patterns Behavior
5/45
The Solution Terminology
Subject and Observer
Publisherand Subscriber
Listeners
Subjects attach and detach
listeners, and notify ofevents Clientsupdate themselves after
receiving a notification
-
8/6/2019 Patterns Behavior
6/45
The Solution II Heres an abstractobserver:
class Observer {
void update() = 0;
}
Concreteobserverssuch as
classChartwill inheritObserver
-
8/6/2019 Patterns Behavior
7/45
The Solution III Heresthe (concrete!)subject:
class Subject {
void attach(Observer *o){ observers.add(o); }
void detach(Observer *o)
{ observers.remove(o); }
void notify() {
for i in observers doo->update();
}protected:
List observers;
}
-
8/6/2019 Patterns Behavior
8/45
The Solution IV Bothsubject and observerwill
usually inherit fromotherclasses
aswell Ifmultiple inheritance isnot
available,theobservermust be a
separateclassthathas a reference
tothechartobject and updates it
Java has a special mechanism
Inner classes tomakethiseasier
-
8/6/2019 Patterns Behavior
9/45
The UML
-
8/6/2019 Patterns Behavior
10/45
The Fine Print Observingmorethanonesubject
Update must include anextra
argumenttotell who isupdating
Observingonly certainevents
Attach must include anextra
argumenttotell whichevents
interestthisobserver
Observingsmall changes
Update includes argumentstotell
whatchanged, forefficiency
-
8/6/2019 Patterns Behavior
11/45
The Fine Print II WhocallsNotify?
Greedy thesubjects,onchange
Lazy theobservers,on query Commonerrors
Forgettingto detach anobjectwhenit is destroyed
CallingNotifyin an inconsistentstate Java includesObserveras partof
thestandard libraries
In packagejava.util
-
8/6/2019 Patterns Behavior
12/45
Known Uses All frameworksof all kinds
MFC,COM,Java, EJB,MVC,
Handleuser interfaceevents
Handle asynchronousmessages
-
8/6/2019 Patterns Behavior
13/45
13. Mediator Encapsulate a complex interaction
to preserve loosecoupling
Preventmany inter-connectionsbetweenclasses,whichmeans
thatchangingtheirbehavior
requiressubclassing all ofthem
Forexample, a dialog box includes
many interactionsof itswidgets.
How dowereusethewidgets?
-
8/6/2019 Patterns Behavior
14/45
The Requirements Awidget is a kind ofcolleague
Colleague dontknow aboutthe
interactionsthey participate inCan bereused fordifferent dialogs
Colleagues dontknow aboutothers
Allowonly O(n) connections Easy tochange interactions
-
8/6/2019 Patterns Behavior
15/45
The Solution All colleaguestalkwith a mediator
Themediatorknows all colleagues
Whenevera colleaguechanges, it
notifies itsmediator
Themediatorcodesthe interaction
logic, and callsoperationsonothercolleagues
-
8/6/2019 Patterns Behavior
16/45
The Solution II Anexample interaction:
-
8/6/2019 Patterns Behavior
17/45
The Solution III Only O(n) connections:
-
8/6/2019 Patterns Behavior
18/45
The UML
-
8/6/2019 Patterns Behavior
19/45
The Fine Print The interaction logic (mediator) and
colleaguescan bereused separately
and subclassed separately Protocols aresimplersincen-to-1
relationsreplacen-to-mrelations
Abstractmediatorclass isunnecessary
iftheresonly onemediator Observerormediator?
One-to-many ormany-to-many?
Should the logic becentralized?
-
8/6/2019 Patterns Behavior
20/45
Known Uses Widgets in a user interface
Delphi and VB hidethis pattern
Connectivity constraints in diagrams
-
8/6/2019 Patterns Behavior
21/45
14. Iterator withoutexposing itsrepresentation
Anextremely common pattern
Forexample, a listshould support
forward and backward traversals
Certainly not by exposing its
internal data structure
Addingtraversal methodstoLists
interface is a bad idea
-
8/6/2019 Patterns Behavior
22/45
The Requirements Traversal operationsshould be
separate fromLists interface
Allowseveral ongoingtraversalsonthesamecontainer
Reuse: itshould be possibletowrite algorithmssuch asfindItem
thatworkon any kind of list
-
8/6/2019 Patterns Behavior
23/45
The Solution Define an abstract iteratorclass:
class Iterator {
void first() = 0;
void next() = 0;
bool isDone() = 0;
G* item() = 0;}
-
8/6/2019 Patterns Behavior
24/45
The Solution II Each data structure implementation
will also implement an iteratorclass:
ListIterator HashTableIterator
FileIterator
StringIterator
Each data structurecanoffermorethanone iterator:
Forward and backward iterators
Preorder, inorder, postorder
-
8/6/2019 Patterns Behavior
25/45
The Solution III Forexample:class BackwardArrayIterator
: public Iterator
{
Array *container;
int pos;
public:
BackwardArrayIterator(Array *a){ container = a; first(); }
next()
{ --pos; }
// other methods easy
}
-
8/6/2019 Patterns Behavior
26/45
The Solution IV A data structures interfaceshould
return iteratorson itself:
class List{
Iterator* getForwardIterator()
{ return new
ListForwardIterator(this); }
Iterator* getBackwardIterator()// similarly
}
Nowevery LinkedListobjectcanhave
many active iterators
-
8/6/2019 Patterns Behavior
27/45
The Solution V Writing functions forcontainers:
void print(Iterator* it)
{
for (it->first();!it->isOver();it->next())
cout item();
}
Usingthem:print(myList->getBackwardIterator());
print(myTable->getColumnItr(Age));
print(myTree->getPostOrderIterator());
-
8/6/2019 Patterns Behavior
28/45
The Solution VI Generic algorithmscan bewritten:
G* findItem(Iterator* it,
G *element){
while (!it->isOver())
{
if (it->item() == element)
return element;it->next();
}
return NULL;
}
-
8/6/2019 Patterns Behavior
29/45
The Requirements II Some iterators aregeneric:
Traverseevery nth item
Traverse itemsthat pass a filterTraverseonly firstn items
Traverse a computed viewof items
Such iteratorsshould becoded once
Itshould beeasy tocombinesuchiterators and add newones
Theiruseshould betransparent
-
8/6/2019 Patterns Behavior
30/45
The Solution Usethe Decoratordesign pattern
Forexample,FilteredIterator
receives another iteratorand thefiltering function in itsconstructor
It delegates all callsto its internaliteratorexceptfirst() and next():
void next() {do it->next()
while (!filter(it->item() &&!it->isOver());
}
-
8/6/2019 Patterns Behavior
31/45
The Solution II It istheneasy tocombinesuch
generic iterators
Printsquarerootsofthe first100positiveelements in a list:print(new LimitedIterator(100,
new ComputedIterator(sqrt,
new FilteredIterator(positive,
list->getForwardIterator()))));
Adding an abstractDecoratorIteratorreducescodesize ifmany exist
-
8/6/2019 Patterns Behavior
32/45
The UML
-
8/6/2019 Patterns Behavior
33/45
The Fine Print Everything is a container
Characterstrings
Files, bothtext and records
Socketstreamsoverthenet
Theresultof a database query
The bitsof an integer
Streamofrandomorprimenumbers
This allowsreusingtheprint,findand
otheralgorithms forall ofthese
-
8/6/2019 Patterns Behavior
34/45
The Fine Print II Iteratorsmay have privileged access
They canencapsulatesecurity rights
Kindsof abstract iterators
Direct access iterators
Accessthe previous item
Robustness issues Isthe iteratorvalid after insertionsor
removals fromthecontainer?
Iterators and theComposite pattern
-
8/6/2019 Patterns Behavior
35/45
Known Uses All majorstandard librariesof
popularprogramming languages
STL forC++ThenewJava containers
New libraries forfile,network and
database access inC++conform
toSTLs iterators aswell
-
8/6/2019 Patterns Behavior
36/45
15. Visitor Separatecomplex algorithmson a
complex data structure fromthe
structuresrepresentation Forexample, a document is a
compositestructure involved in
many complexoperations
Spell check,grammarcheck,hyphenation, auto-format,
How dowe avoid clutteringGlyph
subclasseswith all thiscode?
-
8/6/2019 Patterns Behavior
37/45
The Requirements Encapsulatecomplex algorithms
and theirdata inone place
Outsidethe data structure Easily support different behavior
forevery kind ofGlyph
Easily add newtools
-
8/6/2019 Patterns Behavior
38/45
The Solution Say hellotoclassVisitor:
class Visitor {
public:void visitImage(Image *i) { }
void visitRow(Row *r) { }
void visitTable(Table *t) { }
// so on for every Glyph type
}
Every tool is a subclass:class SpellChecker : public Visitor
-
8/6/2019 Patterns Behavior
39/45
The Solution II Add toGlyphs interfacethe ability to
accept visitors:
void accept(Visitor *v) = 0;
Every glyphsubclass accepts a
visitorby an appropriatecallback:class Image : public Glyph {
void accept(Visitor *v)
{ v->visitImage(this); }
Thisway the visitor is activated for
therightkind ofglyph,with its data
-
8/6/2019 Patterns Behavior
40/45
The Solution III Initiating a spell check (oneoption):
Create a SpellCheckerobject
root->accept(sc); Graphicnon-textglyphswill just
ignorethe visit
This iswhy Visitorincludes default
empty method implementations Compositeglyphs also donothing
They can forward the visitto alltheirchildren. Thiscan becodedonce inCompositeGlyph
-
8/6/2019 Patterns Behavior
41/45
The Solution IV Easy to add operations
Word countoncharacters
Filterssuch assharpenon images
Page layoutchangeson pages
Workson any glyph
In particular, a dynamicselectionas long as its a compositeglyph
Adding a tool doesnotrequire
recompilationofGlyph hierarchy
-
8/6/2019 Patterns Behavior
42/45
The UML
-
8/6/2019 Patterns Behavior
43/45
The Fine Print The big problem: addingnewGlyph
subclasses ishard
Requires small additionofVisitor, andrecompilationof all its subclasses
How dowetraversethestructure?
Using an iterator
From inside the accept() code
From inside the visitxxx() code
Visitors arereally just a workaround
duetothe lackofdouble dispatch
-
8/6/2019 Patterns Behavior
44/45
Known Uses Document Editors
Spell Check,Auto-Format,
Photo EditorsFilters & Effects
Compilers
Code production, pretty printing,tests,metrics and optimizations
onthesyntaxtree
-
8/6/2019 Patterns Behavior
45/45
Summary Patternof patterns
Encapsulatethe varying aspect
Interfaces Inheritance describes variants
Composition allows a dynamic
choice between variants
Design patterns areold,well known
and thoroughly tested ideas
Overtwenty years!