You are on page 1of 8

research summaries arid

exllerlence r epolres

Peter Coad

Object-Oriented Patterns
his article explores patterns, how to find them, presents some patterns for object-
oriented analysis (OOA) and object-oriented design (OOD) as well as providing
examples and guidelines for applying them. ® • • • • ® • • • • ® • #

Patterns Apply tO With each p a t t e r n , small piece- Look more carefully...to find out
Many DiSciplines work is s t a n d a r d i z e d into a larger what it really is that is repeating
W h a t is a p a t t e r n ? c h u n k or unit. Patterns b e c o m e the there .... Beyond its elements, each
b u i l d i n g blocks for design a n d con- building [or town] is defined by
Pattern. A fully realized form,
certain patterns of relationships
original, or model accepted or struction. F i n d i n g a n d a p p l y i n g
among the elements.... These rela-
proposed for imitation: something p a t t e r n s indicates progress in a
tionships are not extra, but neces-
regarded as a normative example field o f h u m a n e n d e a v o r . sary to the elements .... The ele-
to be copied; archetype; exemplar
ments themselves are patterns of
[10]. HOW do People Discover relationships [2].
M a n y fields use p a t t e r n s in various Patterns?
ways: I n music a n d literature, a pat- I n his book The Timeless Way of A n d what h a p p e n s w h e n o n e
t e r n is the c o h e r e n t structure o r Building [2], n o t e d architect Chris- finds a p a t t e r n ? O n e begins to t h i n k
design o f a song or book. I n art, a t o p h e r A l e x a n d e r e x a m i n e s the with that new b u i l d i n g block, r a t h e r
p a t t e r n is the c o m p o s i t i o n or p l a n i m p o r t a n c e o f architectural pat- t h a n with littler pieces.
o f a work o f graphic or plastic art. terns: And finally, the things which seem
I n architecture, a p a t t e r n is a n ar- ..,every place is given its character like elements dissolve, and leave a
chitectural design or style. by certain patterns of events that fabric of relationships behind,
I n psychology, a p a t t e r n is a keep on happening there.... These which is the stuff that actually re-
t h i n k i n g m e c h a n i s m that is basic to patterns of events are locked in peats itself, and gives the structure
the b r a i n ' s o p e r a t i o n , h e l p i n g o n e with certain geometric patterns in to a building or a town [2].
to perceive things quickly [1]. I n the space. Indeed, each building
archeology, a p a t t e r n is a g r o u p o f and each town is ultimately made
out of these patterns in the space, HOW Can One Find Patterns
phases h a v i n g several distinguish- and out of nothing else; they [pat- for OOA and OOD?
i n g a n d f u n d a m e n t a l features in terns in the space] are the atoms So what is the i m p a c t o f Alexan-
c o m m o n . I n linguistics, a p a t t e r n is and molecules from which a build- der's insights o n a d v a n c i n g O O A
the m a n n e r in which smaller units ing or a town is made [2]. a n d O O D ? O b j e c t - o r i e n t e d meth-
of l a n g u a g e are g r o u p e d into larger ods t e n d to focus o n the lowest-level
units. Patterns are m o r e t h a n j u s t the b u i l d i n g block: the class a n d its ob-
I n d r e s s m a k i n g , a p a t t e r n is a smallest e l e m e n t s in a n e n d e a v o r . jects [3, 4, 5, 9, 11].
pleasing shape that is applied re- On the geometric level, we see cer-
tain physical elements repeated Object. A p e r s o n , place, thing,
peatedly. I n decorating, a p a t t e r n is
endlessly, combined in an almost event, o r concept.
a design or figure a p p e a r i n g in fur-
n i t u r e or a n accessory. I n m a n u f a c - endless variety of combinations....
Class. A description o f a n u m -
It is puzzling to realize that the
t u r i n g , a p a t t e r n is the shape or ber o f objects which have cer-
elements, which seem like elemen-
style of a m a n u f a c t u r e d form. I n tary building blocks, keep varying, tain likenesses or c o m m o n
aviation, a p a t t e r n is a collection o f and are different every time that traits.
approaches, t u r n s , a n d altitudes they occur .... If the elements are (derived from [10])
prescribed for a n a i r p l a n e that is different every time that they
c o m i n g in for a l a n d i n g . I n b r o a d - occur, evidently then, it cannot be Classes a n d objects c o r r e s p o n d to
casting, a p a t t e r n is a s t a n d a r d dia- the elements themselves which are A l e x a n d e r ' s constantly repeating,
g r a m for testing television circuits. repeating in a building or town; lowest-level elements. Patterns o f
I n numismatics, a p a t t e r n is a these so-called elements cannot be lowest-level e l e m e n t s a n d relation-
the ultimate "atomic" constituents
s p e c i m e n of a p r o p o s e d coin or ships b e t w e e n t h e m f o r m a b u i l d i n g
of space [2].
coin design. I n chess, a p a t t e r n is a block for m o r e effective O O A a n d
set o f moves that may be applied in T o find patterns, what does o n e O O D . T o find a p a t t e r n a m o n g
a n overall strategy [10]. look for? some lowest-level e l e m e n t s (classes

152 September 1992/VtJI.35, No.9/COMMUNICATIONSOF THE ACM


research summaries and
experience reports

and objects), one must look at the Seven Patterns, Seven done on its behalf. Note that the
relationships between them. Examples, and Guidelines association connection (1) captures
Object-oriented methods already This section begins with notation, the association for future queries
emphasize certain patterns of rela- followed by a presentation of the about these objects and (2) captures
tionships, including generalization- following patterns: item descrip- (for the sender) "to whom to send a
specialization, whole-part, associa- tion; time association; event log- message."
tion, and messaging [3, 4, 9]. Such ging; roles played; state across a An example. A "legal event" object
relationships tie the lowest-level collection; behavior across a collec- knows its date and time; it also
building blocks together. tion; and broadcast. With each pat- knows about (and ties together, in
Some have investigated applica- tern discussed, examples and association) some n u m b e r of
tion frameworks [7], a skeleton of guidelines are provided. "owner" objects and exactly one
classes, objects, and relationships "vehicle" object. To calculate a fee,
grouped together for building a Notation a "legal event" object sends the
specific application. Most of these This article uses the notation sum- message "assess tax type" to its cor-
application frameworks are pri- marized in Figure 1. responding owner object(s) and
marily human interaction skele- then sends the message "categorize
tons, providing a more systematic "Item Description" Pattern vehicle" to its corresponding vehi-
approach to building window inter- Figure 2 illustrates the "item de- cle object. An "owner" object knows
faces. Examples include Apple's scription" pattern. its name and address; it also knows
MacApp (for building a Mac inter- The pattern. T h e item description about some number of correspond-
face), Borland's ObjectWindows, pattern consists of an "item" object ing "legal event" objects. A "vehi-
and the model-view-controller ar- (i.e., an object of the class "item") cle" object knows its number and
chitecture within ParcPlace Sys- and an "item description" object. style; it also knows about some
tem's Objectworks [6, 8]. An "item description" object has number o f corresponding "legal
attribute values which may apply to event" objects.
But other combinations--ones more than one "item" object; an Guidelines for use. Use this pattern
likely to be applicable multiple "item" object has its own individual whenever the system is responsible
times within a single application, assignment of attribute values. to know an association between two
and likely to be applicable across An example. An "aircraft" object or more objects and to know or do
many different kinds of applica- knows its own tail number (e.g., something about that association.
t i o n s - h a v e not been investigated N123ABC); it also knows about
to date. Little is known about pat- exactly one "aircraft description" "Event Logging" Pattern
terns--combinations of certain object. An "aircraft description" Figure 4 illustrates the "event log-
classes and objects, with relation- object knows its own manufacturer ging" pattern.
ships between t h e m - - t h a t apply (e.g., Boeing), model (e.g., 747- The pattern. A "device" object
again and again in different O O A 400), and standard cruising range monitors an external device; the
and OOD efforts. Exploring such (e.g., 8,333 miles); it also may know object is responsible for detecting
patterns is the purpose of this short about some number of "aircraft" that an event has occurred; the ob-
article. objects that depend on that infor- ject is also responsible for initiating
mation. the response to that event. Part of
An object-oriented pattern is an ab- Guidelines for use. Use this pattern that response may be to log the
straction of a doublet, triplet, or other when some attribute values may event's occurrence. When this is the
small grouping of classes that is likely to apply to more than one object in a case, a "device" object sends the
be helpful again and again in object- class. message "create" to the "event re-
oriented development. membered" class to create a new
"Time Association" Pattern object in that class, one with histori-
Patterns are found by trial-and- Figure 3 illustrates the "time associ- cal values. A "device" object may
error and by observation. By build- ation" pattern. know about some number o f "event
ing many object-oriented models The pattern. A "participant 1" ob- remembered" objects; an "event
and by observing many applications ject may know about (be associated remembered" object must know
of the lowest-level building blocks with) a "participant 2" object. If one about a corresponding "device"
and the relationships established needs to express attributes or ser- object.
between them, one can find pat- vices regarding that association, An example. A "temperature sen-
terns. With such patterns, as Alex- then an object from "time associa- sor" object monitors an actual tem-
ander observed, "the things which tion" is needed. A "time associa- perature sensor, looking for a
seem like elements dissolve," and tion" object often sends messages to threshold violation; to do its job, it
one is able to use a higher-level its participating objects in order to knows its operational state and its
building block for OOA and OOD. get values or get a subcalculation threshold. Once it detects that a

COMMUNICATIONS OF THE ACM/September 1992/Vol.35, No.9 153


research summaPles and
experience reports

I ClassName3
1
i
This is a 'class-&-object" symbol. Attribute1 Attributes are listed In the center section.
ClassNamel Attributes depict what an oblect knows.
The heavy border represents a class. Attribute2
The lighter border represents
an object In that class.

J
iii i
ClassName2 This is a "class" symbol.
It has no directly corresponding Services are listed In the lower section.
objects. Services define what an object does.

i 1
GeneralizationClass

U This is a generalization-
specialization (gen-spec) structure. O,~rnl This is a whole-part structure.
P
SpecializationClass A speclalizaUon class Inherits
I1 The range or limit markings in
the attributes and services defined I ~ l this example indicate that a
In the generalizationclass. whole object may know about
some number of part objects,
and that a part object knows
about one whole object.

i om I
Sender The solid connecting line Is The patterned (dashed) arrow
Receiver 1
an association connection, is a message connection. It
Indicating that one object needs portrays dynamic scenarios
to know about another object. (threads of execution).

A subject Is used to guide a reader through


~ . c ~ a"chunk"o, an overallmodel.

and time, m e a s u r e d value, and

U
m o n i t o r e d threshold.
"Item description" pattem Guidelines for use. Use whenever
an event is detected, and you need
to log its occurrence to s u p p o r t
after-the-fact analysis or to meet
legal requirements.

i i 1
AircraftDescription
1 manufacturer "Roles Played" Pattern
An example tailNumber model
O,m standardCruisingRange
Figure 5 illustrates the "roles
played" pattern.
The pattern. A "player" object has
attribute values and services that
apply over time. A player object is
F i g u r e 11. OOA and OOD notation used threshold violation has occurred, it always a player object. At times, a
in this article
sends a message to the "threshold player object "wears different hats,"
I[=lgure :!. "Item description" [oattern violation" class to create a new ob- playing one or more roles. Often,
and example ject in that class with values for date starting and e n d i n g times are corn-

lS4 September 1992/Vol.35, N o . 9 / C O M M U N I C A T I O N S OF T H E A C M


research summaries anll
experience reports

I ( Participant1 ~I Tm
i eAss°ca i t°in
i~ I Participant2
"Timeassociation"pattern dateTmie
cacl ua
l te

I! Owner ' 1,m LegalEvent il1


II .......1,m]~
ri_numberV°h,o,o
II name
An example II
address dateTime I 1 ~ 1 1 s~/le
~L~assessTaxType calculateFee ~ ~ assessVehicl_eCategory

Figure 3. "Time association" pattern and example

,,,,,,oov,c. ~0.~ ,[[ EventRemembered


dataTime
"Eventlogging"pattern state
monitor ~ ~ ~ t value
I

IIII
ThresholdViolation

An example i montioFrorTrheshodl V,oial toi n0,m


ii•m[p•ratu •s•nsor
dateTime
measuredValue
monitoredThreshold
create

Figure 4. "Event logging" pattern and example

,,Ro,esp,aye, p ,,ern P'aYer An example

o.?
}1
n~v'°°°
copyNumber

VideoRole
dateTimeStart dateTimeStart
dateTimeEnd dateTimeEnd

,L,L
i-, ......... I L
i Ret urnedVideoRol
~e
I ....

RenetdVdieoRoel status
i durato
in
wacthForOverdue
Figure S. "Roles played" pattern and example

COMMUNICATIONSOFTHE ACM/Scptcmber 1992/Vo1,35, No.9 lSS


releor¢h suntnlorles alld
experience reports

mon to all such roles. Roles are spe-


=State acrossa collection"pattem An example cialized, according to the attributes
and services needed in each role.
I Collection ~ Aircraft This pattern accommodates large
numbers of roles, combinations of

+ ~
o.?,
altitude
roles, and changes in roles much
more graciously than an application
of multiple inheritance permits.
An example. A "video" object
knows its name and copy number;
it also knows about corresponding
"rented video role" and "returned
memberAttribute ~ ratedPower video role" objects. Each role object
knows its starting date and time and
(eventually) its ending date and
time. The "rented video role"
knows its duration, and watches for
it becoming overdue; the "returned
"Behavior across a collection" pattern An example video role" knows its status (i.e.,
whether or not it is ready to be
I Collection CallCalulation rented again).
Guidelines for use. Use this pattern
collectionService 1 selectNextCall whenever you have a player object
-Oom
-7 T which remains the same old player
object, but has different attributes
and services, depending on the
"hats" the player may wear. Use this
Call pattern to model large numbers of

Member timeOfArrival
priority Figure 6. "State across a collection"
originatingNumber pattern and example
memberService
route
ratelmportance Figure 1. "Behavioracrossa collec-
tion" pattern and example
Figure 8. "Broadcast"pattern and
example

=Broadcast" pattern

I Receivlngltem
Broadcastlngltem
messageToGetChange
recelveChangeNotlflcatlon broadcastChangeNoUflcaUon
sendMessageToGetChange
i

An example

I HumanlnteracUonView DatalnteractlonView
messageTolnvokeAction messageToGetChange
messageToGetChange
0,m Model load
getUserlnput receiveChangeNotification
sendMessageTolnvokeActlon broadcastChangeNotlflcaUon sendMessageToGetChange
recelveChangeNotiflcatlon update
sendMessageToGetChange save
updateDisplay

I S6 September 1992/Vol.35,NO.9/COMMUNICATIONS OF THE ACM


research summaries and
experience PepoPts

roles, combinations of roles, and this example, can know enough (all input and sends a message to in-
changes in roles; this approach is the call objects waiting to be ser- voke action to the corresponding
more concise and flexible than at- viced) and do enough (select the "model" object. At some point in
tempting to use multiple inheri- next call, based on a selection algo- time, when a change does occur, a
tance in this situation. rithm) to carry out this responsibil- "model" object broadcasts a change
ity. So the "call collection" object is notification to its dependent
"State Across a Collection" set up to do just that. Note that such "human interaction view" objects.
Pattern a collection does exist in the do- T h e n each dependent "human in-
Figure 6 illustrates the "state across main; it is called a queue; but the teraction view" object sends a mes-
a collection" pattern. words "call collection" take the sage to get the change; on receipt of
The pattern. A "collection" object model away from being locked into the change, the "human interaction
knows its state; this state applies to a "first in, first out" mentality; and view" updates its display. In
the collection and may also apply to the name helps one to focus on ParcPlace System's Objectworks,
its parts, by physical or temporal behavior across the collection only, this application of a broadcast pat-
proximity. And each "member" not pulling up any of the work that tern is called model-view-controller
object has its own state, too. each call knows enough to do itself. (MVC); the innovative work on
An example. An aircraft is an as- Guidelines for use. Use this pattern MVC [6, 8] is the basis for abstract-
sembly (collection) of engines; in whenever there is whole-part in a ing and then applying the "broad-
other words, an "aircraft" object business domain or implementation cast" pattern.
may know about some number of domain, and a behavior (i.e., one or On the right side of Figure 8, the
"engine" objects. (Note that while more services) applies across the pattern is used to isolate the impact
most aircraft have engines, gliders whole collection. Caution: make the of data management. Again, this is
do not.) Each "engine" object member objects do as much as they done to simplify both parts; and it is
knows its own rated power. Each can with what they know; only put done to increase the likelihood of
"aircraft" object knows about its al- behavior that really applies across reuse for each part. At some point
titude; this particular attribute the collection up in the "collection" in time, when a change does occur,
value applies to the whole, and also object; in doing this, the active side a "model" object broadcasts a
to its parts, by physical proximity. of the objects is better partitioned change notification to its depen-
Guidelines for use. Use this pattern by the participating classes, rather dent "data interaction view" objects.
whenever there is whole-part in a than having a centralized manager T h e n each dependent "data inter-
business domain or implementation with subordinate data-hiders. action view" object sends a message
domain, and one or more attributes to get the change; on receipt of the
apply to the whole (the collection). "Broadcast" Pattern change, the "data interaction view"
Figure 8 illustrates the "broadcast" updates its data representation
"Behavior Across a Collection" pattern. (e.g., its tables). The "data interac-
Pattern The pattern. This pattern is used tion view" knows how to save and
Figure 7 illustrates the "behavior to communicate complex changes load its data representations into a
across a collection" pattern. between one major section of an storage device.
The pattern. A "collection" object O O A / O O D model with another Actually, this example is some-
has behavior that applies across an major section. Whenever it what simplified; often, in the appli-
entire collection of its "member" changes, a "broadcasting item" ob- cation of this pattern, the interact-
objects. And each "member" object ject broadcasts a change notifica- ing objects are actually objects of
performs actions, knowing (by tion to the "receiving item" objects classes that are specializations of the
means of its attributes) how to per- that it knows about. A notified "re- classes shown in this example. Yet
form, without needed coordination ceiving item" object then sends a the same basic pattern applies, even
with other "member" objects. message to the "broadcasting item" when specialization classes are in-
An example. A "call" object knows to get the change; once it gets the volved.
its time of arrival, priority, and its change, a "receiving item" object Guidelines for use. Use this pattern
originating number. T h e "call" ob- takes whatever action is necessary to establish interactions between
ject (the abstraction, not the elec- in light of the change. major O O A / O O D parts in a way
tronic signal it works on) also knows An example. On the left side of that the two sections stay cleanly
how to route itself. It can even rate Figure 8, the pattern is applied to separated, rather than becoming
its importance. keep h u m a n interaction distinct hopelessly intertwined. Be sure to
But which call gets to go next? from business domain classes. This use this pattern to separate business
T h e "call" object does not know is done to simplify both parts; and it domain classes from h u m a n inter-
enough to make the actual selec- is done to increase the likelihood of action classes, and to separate busi-
tion. Yet a collection of all calls, reuse for each part. A "human in- ness domain classes from data man-
called a "call collection" object in teraction view" object gets user agement classes.

COMMUNICATIONSOF TH e: ACM/September 1992/Vo1.35, No.9 I S7


resecarch summaries and
experiefla:o reports

Applying Six Patterns tematic a p p r o a c h to discovering Oriented Analysis. Second ed. Pren-
In One Example and cataloging patterns? Is there a tice Hall, Englewood Cliffs, N.J.,
Figure 9 is a larger example show- hierarchy o f patterns? How does 1991.
ing how patterns can be combined one look at examples and derive 5. Coad, P. and Yourdon, E. Object-
into larger models. This one model guidelines for best usage? W h a t Oriented Design. Prentice Hall, En-
applies six patterns. strategies can be used for connect- glewood Cliffs, N.J., 1991.
ing one pattern to another? W h e n 6. Goldberg, A. Information models,
Summary and does the occurrence o f one pattern views, and controllers. Dr. Dobb's J.
Recommendations imply the need for another com- (July 1990).
A pattern is a fully realized form panion pattern? 7. Johnson, R. and Wirfs-Brock, R.
original, or model accepted or pro- Patterns are the molecules from Object-oriented frameworks. Tuto-
posed for imitation. With patterns, which one may apply O O A and rial notes. In Proceedings of ACM
small piecework is standardized O O D m o r e effectively. OOPSLA (1991).
into a larger chunk or unit. Patterns
become the building blocks for de- Acknowledgments 8. Leibs, D. and Rubin, K. Reimple-
menting model-view-controller. The
sign and construction. Finding and T h e author thanks Mark Mayfield,
Smalltalk Report (Mar./Apr. 1992).
applying patterns indicates prog- Jill Nicola, and Teri Roberts for
ress in a field o f h u m a n endeavor. their help in identifying, abstract- 9. Rumbaugh, J., Blaha, M., Premer-
This article is only a very small ing, and applying these p a t t e r n s . n lani, W., Eddy, F. and Lorensen, W.
Object-Oriented Modeling and Design.
beginning o f the work to be done
on investigating, finding, and ap- References Prentice Hall, Englewood Cliffs,
1. Albrecht, K. Brain Power. Prentice N.J., 1991.
plying object-oriented patterns.
Hall, Englewood Cliffs, N.J., 1980.
Additional investigation is n e e d e d 2. Alexander, C. The Timeless Way of 10. Webster's Third New International Dic-
on pattern discovery and usage. Building. Oxford University Press, tionary. Merriam Webster, Inc.,
Given a large n u m b e r o f O O A and 1979. 1986.
O O D results, can one apply a sys- 3. Booch, G. Object-Oriented Design with 11. Wirfs-Brock, R., Wilkerson, B. and
Applications. Benjamin/Cummings, Wiener, L. Designing Object-Oriented
Figure 9. A larger example,applying Redwood City, Ca., 1991. Software. Prentice Hall, Englewood
six patterns 4. Coad, P. and Yourdon, E. Object- Cliffs, N.J., 1990.

"Item description"pattern "State across a collection"pattern


Product description--
sales transaction item
Sales transaction--
sales transaction item
I Pea'oni
"Time association"pattern "Behavior across a collection"pattern name
Customer~sales transaction-- Sales transaction--
employee sales transaction item
"Event logging"pattern
Product description---
reorder event
"Roles played" pattern
Person--person role-- i SalesTransaction 1 I PersonRole ]
customer, employee number 2
dateTime 0,m(
[ dateTime
calcutateTotal

- ProduetDescriptlon [~ SalesTransactionl~I t~em' 1 [~J disc°un`Customer 1 i E,!y;e


productCode
price
0,m 11] quantity
" ~caleulateltemTota':
a~r:~ ~L ~ ~,~calculateDiscountAmount
number i
descrption
numberlnStock
reorderLevel
i getPrice ~ ; ~ Lt~. .ReorderEvent
... 1
autoReorder O,m J| dateTime
I i I status

lS8 OF
September 1992/Vo1.35, No.9/COMMUNICATIONS THE ACM
reseuP¢ll sunlnlorle| lind
experience reports

CR Categories and Subject Descrip- Additional Key Words and Phrases: tin, T X 78759-8864; email: coad@
tors: D.2.1 [Software]: Software Engi- Analysis, design, object-oriented nota- applelink.apple.com or CompuServe
neering - - requirements / specifications; tion and methodology, object-oriented 71210, 3642
D.2.10 [Software]: Software Engi- software engineering, reliable compo-
neering-design; 1.6.0 [Computing nent reusability
Methodologies]: Simulation and Mod- Permission to copy without fee all or part of
eling-general; 1.6.3 [Computing Meth- About the Author: this material is granted provided that the
odologies]: Simulation and Modeling-- PETER COAD is the chair of Object copies are not made or distributed for direct
applications; K.6.3 [Computing Mi- International, Inc. Current research commercial advantage, the ACM copyright
lieux]: Management of Computing and interests include object-oriented meth- notice and the title of the publication and its
Information Systems--software manage- ods, reuse, more effective analysis and date appear, and notice is given that copying
ment; K.6.4 [Computing Milieux]: Man- design tools, and intelligence theories is by permission of the Association for
agement of Computing and Informa- Computing Machinery. To copy otherwise, or
leading to accelerated techology trans-
to republish, requires a fee and/or specific
tion Systems--system management fer. Author's Present Address: Object permission.
General Terms: Design, Experimen- International, Inc., 8140 N. MoPac
tation Expressway, Building 4, Suite 200, Aus- © ACM 0002-0782/92/0900-153$1.50

CARE plants the


most wonderful
seeds on earth.
Seeds of self-sufficiency that help
starving people become healthy;
productive people. And we do it
village by village by village.
Please help us turn cries for help
into the laughter of hope.

COMMUNICATIONS OF THE ACM/September1992/VoL35,No.9 ! 59

You might also like