Design Patterns: Abstraction and Reuse of
Ob ject-Oriented Design
1? 2 3 2
Erich Gamma , Richard Helm , Ralph Johnson , John Vlissides
1
Taligent, Inc.
10725 N. De Anza Blvd., Cup ertino, CA 95014-2000 USA
2
I.B.M. Thomas J. Watson Research Center
P.O. Box 704, Yorktown Heights, NY 10598 USA
3
Department of Computer Science
University of Illinoi s at Urbana-Champaign
1034 W. Spring eld Ave., Urbana, IL 61801 USA
Abstract. We prop ose design patterns as a new mechanism for expressing ob ject-oriented
design exp erience. Design patterns identify, name, and abstract common themes in ob ject-
oriented design. They capture the intent b ehind a design by identifying ob jects, their col-
lab orations, and the distributio n of resp onsibil i ties. Design patterns play many roles in the
ob ject-oriented development pro cess: they provide a common vo cabulary for design, they re-
duce system complexityby naming and de ning abstractions, they constitute a base of ex-
p erience for buildin g reusable software, and they act as building blo cks from which more
complex designs can b e built. Design patterns can b e considered reusable micro-architectures
that contribute to an overall system architecture. We describ e how to express and organize
design patterns and intro duce a catalog of design patterns. We also describ e our exp erience in
applying design patterns to the design of ob ject-oriented systems.
1 Intro duction
Design metho ds are supp osed to promote go o d design, to teach new designers how to design well, and
to standardize the way designs are develop ed. Typically, a design metho d comprises a set of syntactic
notations usually graphical and a set of rules that govern how and when to use each notation. It
will also describ e problems that o ccur in a design, how to x them, and howtoevaluate a design.
Studies of exp ert programmers for conventional languages, however, have shown that knowledge is
not organized simply around syntax, but in larger conceptual structures such as algorithms, data
structures and idioms [1, 7, 9, 27], and plans that indicate steps necessary to ful ll a particular
goal [26]. It is likely that designers do not think ab out the notation they are using for recording
the design. Rather, they lo ok for patterns to match against plans, algorithms, data structures, and
idioms they have learned in the past. Go o d designers, it app ears, rely on large amounts of design
exp erience, and this exp erience is just as imp ortant as the notations for recording designs and the
rules for using those notations.
Our exp erience with the design of ob ject-oriented systems and frameworks [15,17,22, 30, 31]
b ears out this observation. Wehave found that there exist idiomatic class and ob ject structures that
help make designs more exible, reusable, and elegant. For example, the Mo del-View-Controller
MVC paradigm from Smalltalk [19] is a design structure that separates representation from pre-
sentation. MVC promotes exibility in the choice of views, indep endent of the mo del. Abstract
factories [10] hide concrete sub classes from the applications that use them so that class names are
not hard-wired into an application.
?
Work p erformed while at UBILAB, Union Bank of Switzerland, Zurich, Switzerland.
To app ear in ECOOP '93 ConferenceProceedings, Springer-VerlagLecture Notes in Computer Science.
Well-de ned design structures like these have a p ositive impact on software development. A
software architect who is familiar with a go o d set of design structures can apply them immediately
to design problems without having to rediscover them. Design structures also facilitate the reuse of
successful architectures|expressing proven techniques as design structures makes them more readily
accessible to develop ers of new systems. Design structures can even improve the do cumentation and
maintenance of existing systems by furnishing an explicit sp eci cation of class and ob ject interactions
and their underlying intent.
To this end we prop ose design patterns, a new mechanism for expressing design structures.
Design patterns identify, name, and abstract common themes in ob ject-oriented design. They pre-
serve design information by capturing the intent b ehind a design. They identify classes, instances,
their roles, collab orations, and the distribution of resp onsibilities. Design patterns have many uses
in the ob ject-oriented development pro cess:
{ Design patterns provide a common vo cabulary for designers to communicate, do cument, and
explore design alternatives. They reduce system complexityby naming and de ning abstractions
that are ab ove classes and instances. A go o d set of design patterns e ectively raises the level at
which one programs.
{ Design patterns constitute a reusable base of exp erience for building reusable software. They
distill and provide a means to reuse the design knowledge gained by exp erienced practitioners.
Design patterns act as building blo cks for constructing more complex designs; they can b e
considered micro-architectures that contribute to overall system architecture.
{ Design patterns help reduce the learning time for a class library. Once a library consumer has
learned the design patterns in one library, he can reuse this exp erience when learning a new class
library. Design patterns help a novice p erform more like an exp ert.
{ Design patterns provide a target for the reorganization or refactoring of class hierarchies [23].
Moreover, by using design patterns early in the lifecycle, one can avert refactoring at later stages
of design.
The ma jor contributions of this pap er are: a de nition of design patterns, a means to describ e
them, a system for their classi cation, and most imp ortantly, a catalog containing patterns wehave
discovered while building our own class libraries and patterns wehave collected from the literature.
This work has its ro ots in Gamma's thesis [11], which abstracted design patterns from the ET++
framework. Since then the work has b een re ned and extended based on our collective exp erience.
Our thinking has also b een in uenced and inspired by discussions within the Architecture Handb o ok
Workshops at recent OOPSLA conferences [3, 4].
This pap er has two parts. The rst intro duces design patterns and explains techniques to describ e
them. Next we present a classi cation system that characterizes common asp ects of patterns. This
classi cation will serve to structure the catalog of patterns presented in the second part of this pap er.
We discuss how design patterns impact ob ject-oriented programming and design. We also review
related work.
The second part of this pap er the App endix describ es our current catalog of design patterns.
As we cannot include the complete catalog in this pap er it currently runs over 90 pages [12], we
give instead a brief summary and include a few abridged patterns. Each pattern in this catalog is
representative of what we judge to b e go o d ob ject-oriented design. Wehave tried to reduce the
sub jectivity of this judgmentby including only design patterns that have seen practical application.
Every design pattern wehave included works|most have b een used at least twice and have either
b een discovered indep endently or have b een used in a variety of application domains.
2 Design Patterns
A design pattern consists of three essential parts:
1. An abstract description of a class or ob ject collab oration and its structure. The description is
abstract b ecause it concerns abstract design, not a particular design.
2. The issue in system design addressed by the abstract structure. This determines the circum-
stances in which the design pattern is applicable.
3. The consequences of applying the abstract structure to a system's architecture. These determine
if the pattern should b e applied in view of other design constraints.
Design patterns are de ned in terms of ob ject-oriented concepts. They are suciently abstract to
avoid sp ecifying implementation details, thereby ensuring wide applicability, but a pattern may
provide hints ab out p otential implementation issues.
We can think of a design pattern as a micro-architecture. It is an architecture in that it serves
as a blueprint that mayhave several realizations. It is \micro" in that it de nes something less than
a complete application or library.To b e useful, a design pattern should b e applicable to more than
a few problem domains; thus design patterns tend to b e relatively small in size and scop e. A design
pattern can also b e considered a transformation of system structure. It de nes the context for the
transformation, the change to b e made, and the consequences of this transformation.
To help readers understand patterns, eachentry in the catalog also includes detailed descriptions
and examples. We use a template Figure 1 to structure our descriptions and to ensure uniformity
between entries in the catalog. This template also explains the motivation b ehind its structure.
The App endix contains three design patterns that use the template. We urge readers to study the
patterns in the App endix as they are referenced in the following text.
3 Categorizing Design Patterns
Design patterns vary in their granularity and level of abstraction. They are numerous and have
common prop erties. Because there are many design patterns, we need a way to organize them. This
section intro duces a classi cation system for design patterns. This classi cation makes it easy to
refer to families of related patterns, to learn the patterns in the catalog, and to nd new patterns.
Characterization
Creational Structural Behavioral
Jurisdiction Class Factory Metho d Adapter class Template Metho d
Bridge class
Ob ject Abstract Factory Adapter ob ject Chain of Resp onsibil ity
Prototyp e Bridge ob ject Command
Solitaire Flyweight Iterator ob ject
Glue Mediator
Proxy Memento
Observer
State
Strategy
Comp ound Builder Comp osite Interpreter
Wrapp er Iterator comp ound
Walker
Table 1. Design Pattern Space
Design Pattern Name Jurisdiction Characterization
What is the pattern's name and classi cation ? The name should convey the pattern's essence succinctly.A
go o d name is vital, as it will b ecome part of the design vo cabulary.
Intent
What do es the design pattern do? What is its rationale and intent? What particular design issue
or problem do es it address?
Motivation
A scenario in which the pattern is applicable, the particular design problem or issue the pattern ad-
dresses, and the class and ob ject structures that address this issue. This information will help the reader
understand the more abstract description of the pattern that follows.
Applicability
What are the situations in which the design pattern can b e applied? What are examples of p o or
designs that the pattern can address? How can one recognize these situations?
Participants
Describ e the classes and/or ob jects participating in the design pattern and their resp onsibil i ties us-
ing CRC conventions [5].
Collab orations
Describ e how the participants collab orate to carry out their resp onsibili ties .
Diagram
A graphical representation of the pattern using a notation based on the Ob ject Mo deling Technique
OMT [25], to whichwehave added metho d pseudo-co de.
Consequences
How do es the pattern supp ort its ob jectives? What are the trade-o s and results of using the pat-
tern? What do es the design pattern ob jectify? What asp ect of system structure do es it allowtobe
varied indep endently?
Implementation
What pitfalls, hints, or techniques should one b e aware of when implementing the pattern? Are there
language-sp eci c issues?
Examples
This section presents examples from real systems. We try to include at least two examples from di erent
domains.
See Also
What design patterns have closely related intent? What are the imp ortant di erences? With which
other patterns should this one b e used?
Fig. 1. Basic Design Pattern Template
We can think of the set of all design patterns in terms of two orthogonal criteria, jurisdiction
and characterization.Table 1 organizes our current set of patterns according to these criteria.
Jurisdiction is the domain over which a pattern applies. Patterns having class jurisdiction deal
with relationships b etween base classes and their sub classes; class jurisdiction covers static semantics.
The ob ject jurisdiction concerns relationships b etween p eer ob jects. Patterns having comp ound
jurisdiction deal with recursive ob ject structures. Some patterns capture concepts that span juris-
dictions. For example, iteration applies b oth to collections of ob jects i.e., ob ject jurisdiction and
to recursive ob ject structures comp ound jurisdiction. Thus there are b oth ob ject and comp ound
versions of the Iterator pattern.
Characterization re ects what a pattern do es. Patterns can b e characterized as either creational,
structural,or b ehavioral. Creational patterns concern the pro cess of ob ject creation. Structural
patterns deal with the comp osition of classes or ob jects. Behavioral patterns characterize the ways
in which classes or ob jects interact and distribute resp onsibility.
The following sections describ e pattern jurisdictions in greater detail for eachcharacterization
using examples from our catalog.
3.1 Class Jurisdiction
Class Creational. Creational patterns abstract how ob jects are instantiated by hiding the sp eci cs
of the creation pro cess. They are useful b ecause it is often undesirable to sp ecify a class name
explicitly when instantiating an ob ject. Doing so limits exibility; it forces the programmer to
commit to a particular class instead of a particular proto col. If one avoids hard-co ding the class,
then it b ecomes p ossible to defer class selection to run-time.
Creational class patterns in particular defer some part of ob ject creation to sub classes. An exam-
ple is the Factory Metho d, an abstract metho d that is called by a base class but de ned in sub classes.
The sub class metho ds create instances whose typ e dep ends on the sub class in which each metho d
is implemented. In this way the base class do es not hard-co de the class name of the created ob ject.
Factory Metho ds are commonly used to instantiate memb ers in base classes with ob jects created by
sub classes.
For example, an abstract Application class needs to create application-sp eci c do cuments that
conform to the Do cumenttyp e. Application instantiates these Do cument ob jects by calling the
factory metho d DoMakeDo cument. This metho d is overridden in classes derived from Application.
The sub class DrawApplication, say,overrides DoMakeDo cument to return a DrawDo cument ob ject.
Class Structural. Structural class patterns use inheritance to comp ose proto cols or co de. As a
simple example, consider using multiple inheritance to mix two or more classes into one. The result
is an amalgam class that unites the semantics of the base classes. This trivial pattern is quite useful
in making indep endently-develop ed class libraries work together [15].
Another example is the class-jurisdictional form of the Adapter pattern. In general, an Adapter
makes one interface the adaptee's conform to another, thereby providing a uniform abstraction of
di erentinterfaces. A class Adapter accomplishes this by inheriting privately from an adaptee class.
The Adapter then expresses its interface in terms of the adaptee's.
Class Behavioral. Behavioral class patterns capture how classes co op erate with their sub classes
to ful ll their semantics. Template Metho d is a simple and well-known b ehavioral class pattern [32].
Template metho ds de ne algorithms step by step. Each step can invoke an abstract metho d which
the sub class must de ne or a base metho d. The purp ose of a template metho d is to provide an
abstract de nition of an algorithm. The sub class must implement sp eci c b ehavior to provide the
services required by the algorithm.
3.2 Ob ject Jurisdiction
Ob ject patterns all apply various forms of non-recursive ob ject comp osition. Ob ject comp osition
represents the most p owerful form of reusability|a collection of ob jects are most easily reused
through variations on how they are comp osed rather than how they are sub classed.
Ob ject Creational. Creational ob ject patterns abstract how sets of ob jects are created. The Ab-
stract Factory pattern page 14 is a creational ob ject pattern. It describ es how to create \pro duct"
ob jects through an generic interface. Sub classes may manufacture sp ecialized versions or comp osi-
tions of ob jects as p ermitted by this interface. In turn, clients can use abstract factories to avoid
making assumptions ab out what classes to instantiate. Factories can b e comp osed to create larger
factories whose structure can b e mo di ed at run-time to change the semantics of ob ject creation.
The factory may manufacture a custom comp osition of instances, a shared or one-of-a-kind instance,
or anything else that can b e computed at run-time, so long as it conforms to the abstract creation
proto col.
For example, consider a user interface to olkit that provides twotyp es of scroll bars, one for Motif
and another for Op en Lo ok. An application programmer may not want to hard-co de one or the other
into the application|the choice of scroll bar will b e determined by,say,anenvironmentvariable.
The co de that creates the scroll bar can b e encapsulated in the class Kit, an abstract factory that
abstracts the sp eci c typ e of scroll bar to instantiate. Kit de nes a proto col for creating scroll bars
and other user interface elements. Sub classes of Kit rede ne op erations in the proto col to return
sp ecialized typ es of scroll bars. A MotifKit's scroll bar op eration would instantiate and return a
Motif scroll bar, while the corresp onding Op enLo okKit op eration would return an Op en Lo ok scroll
bar.
Ob ject Structural. Structural ob ject patterns describ e ways to assemble ob jects to realize new
functionality. The added exibility inherent in ob ject comp osition stems from the abilitytochange
the comp osition at run-time, which is imp ossible with static class comp osition .
Proxy is an example of a structural ob ject pattern. A proxy acts as a convenient surrogate or
placeholder for another ob ject. A proxy can b e used as a lo cal representative for an ob ject in a
di erent address space remote proxy, to represent a large ob ject that should b e loaded on demand
virtual proxy, or to protect access to the original ob ject protected proxy. Proxies provide a level
of indirection to particular prop erties of ob jects. Thus they can restrict, enhance, or alter an ob ject's
prop erties.
The Flyweight pattern is concerned with ob ject sharing. Ob jects are shared for at least two
reasons: eciency and consistency. Applications that use large quantities of ob jects must pay careful
attention to the cost of each ob ject. Substantial savings can accrue by sharing ob jects instead of
replicating them. However, ob jects can only b e shared if they do not de ne context-dep endent state.
Flyweights have no context-dep endent state. Any additional information they need to p erform their
task is passed to them when needed. With no context-dep endent state, yweights may b e shared
freely. Moreover, it may b e necessary to ensure that all copies of an ob ject stay consistent when one
of the copies changes. Sharing provides an automatic way to maintain this consistency.
Ob ject Behavioral. Behavioral ob ject patterns describ e how a group of p eer ob jects co op erate to
p erform a task that no single ob ject can carry out by itself. For example, patterns such as Mediator
and Chain of Resp onsibility abstract control ow. They call for ob jects that exist solely to redirect
the ow of messages. The redirection may simply notify another ob ject, or it mayinvolve complex
computation and bu ering. The Observer pattern abstracts the synchronization of state or b ehavior.
Entities that are co-dep endent to the extent that their state must remain synchronized may exploit
Observer. The classic example is the mo del-view pattern, in whichmultiple views of the mo del are
noti ed whenever the mo del's state changes.
The Strategy pattern page 17 ob jecti es an algorithm. For example, a text comp osition ob ject
may need to supp ort di erent line breaking algorithms. It is infeasible to hard-wire all such algorithms
into the text comp osition class and sub classes. An alternative is to ob jectify di erent algorithms and
However, ob ject mo dels that supp ort dynamic inheritance, most notably Self [29], are as exible as ob ject
comp osition in theory.
provide them as Comp ositor sub classes. The interface for Comp ositors is de ned by the abstract
Comp ositor class, and its derived classes provide di erentlayout strategies, such as simple line
breaks or full page justi cation. Instances of the Comp ositor sub classes can b e coupled with the text
comp osition at run-time to provide the appropriate text layout. Whenever a text comp osition has
to nd line breaks, it forwards this resp onsibility to its current Comp ositor ob ject.
3.3 Comp ound Jurisdiction
In contrast to patterns having ob ject jurisdiction, which concern p eer ob jects, patterns with com-
p ound jurisdiction a ect recursive ob ject structures.
Comp ound Creational. Creational comp ound patterns are concerned with the creation of recur-
sive ob ject structures. An example is the Builder pattern. A Builder base class de nes a generic
interface for incrementally constructing recursive ob ject structures. The Builder hides details of how
ob jects in the structure are created, represented, and comp osed so that changing or adding a new
representation only requires de ning a new Builder class. Clients will b e una ected bychanges to
Builder.
Consider a parser for the RTF RichText Format do cument exchange format that should b e
able to p erform multiple format conversions. The parser might convert RTF do cuments into 1
plain ASCI I text and 2 a text ob ject that can b e edited in a text viewer ob ject. The problem is
how to make the parser indep endent of these di erent conversions.
The solution is to create an RTFReader class that takes a Builder ob ject as an argument. The
RTFReader knows how to parse the RTF format and noti es the Builder whenever it recognizes text
or an RTF control word. The builder is resp onsible for creating the corresp onding data structure.
It separates the parsing algorithm from the creation of the structure that results from the parsing
pro cess. The parsing algorithm can then b e reused to create anynumb er of di erent data repre-
sentations. For example, an ASCI I builder ignores all noti cations except plain text, while a Text
builder uses the noti cations to create a more complex text structure.
Comp ound Structural. Structural comp ound patterns capture techniques for structuring recur-
sive ob ject structures. A simple example is the Comp osite pattern. A Comp osite is a recursive
comp osition of one or more other Comp osites. A Comp osite treats multiple, recursively comp osed
ob jects as a single ob ject.
The Wrapp er pattern page 20 describ es how to exibly attach additional prop erties and services
to an ob ject. Wrapp ers can b e nested recursively and can therefore b e used to comp ose more complex
ob ject structures. For example, a Wrapp er containing a single user interface comp onent can add
decorations such as b orders, shadows, scroll bars, or services like scrolling and zo oming. To do this,
the Wrapp er must conform to the interface of its wrapp ed comp onent and forward messages to it.
The Wrapp er can p erform additional actions suchasdrawing a b order around the comp onent
either b efore or after forwarding a message.
Comp ound Behavioral. Finally, b ehavioral comp ound patterns deal with b ehavior in recursive
ob ject structures. Iteration over a recursive structure is a common activity captured by the Iterator
pattern. Rather than enco ding and distributing the traversal strategy in each class in the structure,
it can b e extracted and implemented in an Iterator class. Iterators ob jectify traversal algorithms over
recursive structures. Di erent iterators can implement pre-order, in-order, or p ost-order traversals.
All that is required is that no des in the structure provide services to enumerate their sub-structures.
This avoids hard-wiring traversal algorithms throughout the classes of ob jects in a comp osite struc-
ture. Iterators may b e replaced at run-time to provide alternative traversals.
4 Exp erience with Design Patterns
Wehave applied design patterns to the design and construction of a several systems. We brie y
describ e two of these systems and our exp erience.
4.1 ET++SwapsManager
The ET++SwapsManager [10] is a highly interactive to ol that lets traders value, price, and p erform
what-if analyses for a nancial instrument called a swap. During this pro ject the develop ers had to
rst learn the ET++ class library, then implement the to ol, and nally design a framework for cre-
ating \calculation engines" for di erent nancial instruments. While teaching ET++ we emphasized
not only learning the class library but also describing the applied design patterns. We noticed that
design patterns reduced the e ort required to learn ET++. Patterns also proved helpful during de-
velopment in design and co de reviews. Patterns provided a common vo cabulary to discuss a design.
Whenever we encountered problems in the design, patterns help ed us explore design alternatives
and nd solutions.
4.2 QOCA: A Constraint Solving To olkit
QOCA Quadratic Optimization Constraint Architecture [14,15] is a new ob ject-oriented
constraint-solving to olkit develop ed at IBM Research. QOCA leverages recent results in symb olic
computation and geometry to supp ort ecient incremental and interactive constraint manipulation.
QOCA's architecture is designed to b e exible. It p ermits exp erimentation with di erent classes of
constraints and domains e.g., reals, b o oleans, etc., di erent constraint-solving algorithms for these
domains, and di erent representations doubles, in nite precision for ob jects in these domains. QO-
CA's ob ject-oriented design allows parts of the system to b e varied indep endently of others. This
exibilitywas achieved, for example, by using Strategy patterns to factor out constraint solving
algorithms and Bridges to factor out domains and representations of variables. In addition, the
Observable pattern is used to propagate noti cations when variables change their values.
4.3 Summary of Observations
The following p oints summarize the ma jor observations wehave made while applying design patterns:
{ Design patterns motivate develop ers to go b eyond concrete ob jects; that is, they ob jectify con-
cepts that are not immediately apparent as ob jects in the problem domain.
{ Cho osing intuitive class names is imp ortant but also dicult. Wehave found that design pat-
terns can help name classes. In the ET++SwapsManager's calculation engine framework we
enco ded the name of the design pattern in the class name for example CalculationStrategy or
TableAdaptor. This convention results in longer class names, but it gives clients of these classes
a hint ab out their purp ose.
{ We often apply design patterns after the rst implementation of an architecture to improve its
design. For example, it is easier to apply the Strategy pattern after the initial implementationto
create ob jects for more abstract notions like a calculation engine or constraint solver. Patterns
were also used as targets for class refactorings. We often nd ourselves saying, \Make this part of
a class into a Strategy," or, \Let's split the implementation p ortion of this class into a Bridge."
{ Presenting design patterns together with examples of their application turned out to b e an
e ectiveway to teach ob ject-oriented design by example.
{ An imp ortant issue with any reuse technology is how a reusable comp onent can b e adapted to
create a problem-sp eci c comp onent. Design patterns are particularly suited to reuse b ecause
they are abstract. Though a concrete class structure may not b e reusable, the design pattern underlying it often is.
{ Design patterns also reduce the e ort required to learn a class library. Each class library has a
certain design \culture" characterized by the set of patterns used implicitlyby its develop ers.
A sp eci c design pattern is typically reused in di erent places in the library. A client should
therefore learn these patterns as a rst step in learning the library. Once they are familiar with
the patterns, they can reuse this understanding. Moreover, b ecause some patterns app ear in
other class libraries, it is p ossible to reuse the knowledge ab out patterns when learning other
libraries as well.
5 Related Work
Design patterns are an approach to software reuse. Krueger [20]intro duces the following taxonomy
to characterize di erent reuse approaches: software comp onent reuse, software schemas, application
generators, transformation systems, and software architectures. Design patterns are related to b oth
software schemas and reusable software architectures. Software schemas emphasize reusing abstract
algorithms and data structures. These abstractions are represented formally so they can b e instan-
tiated automatically. The Paris system [18] is representativeofschema technology. Design patterns
are higher-level than schemas; they fo cus on design structures at the level of collab orating classes
and not at the algorithmic level. In addition, design patterns are not formal descriptions and cannot
b e instantiated directly.We therefore prefer to view design patterns as reusable software architec-
tures. However, the examples Krueger lists in this category blackb oard architectures for exp ert
systems, adaptable database subsystems are all coarse-grained architectures. Design patterns are
ner-grained and therefore can b e characterized as reusable micro-architectures.
Most researchinto patterns in the software engineering community has b een geared towards
building knowledge-based assistants for automating the application of patterns for synthesis that
is, to write programs and analysis in debugging, for example [13, 24]. The ma jor di erence b etween
our work and that of the knowledge-based assistant community is that design patterns enco de higher-
level exp ertise. Their work has tended to fo cus on patterns likeenumeration and selection, which
can b e expressed directly as reusable comp onents in most existing ob ject-oriented languages. We
b elieve that characterizing and cataloging higher-level patterns that designers already use informally
has an immediate b ene t in teaching and communicating designs.
A common approach for reusing ob ject-oriented software architectures are ob ject-oriented frame-
works [32]. A framework is a co di ed architecture for a problem domain that can b e adapted to solve
sp eci c problems. A framework makes it p ossible to reuse an architecture together with a partial
concrete implementation. In contrast to frameworks, design patterns allow only the reuse of ab-
stract micro-architectures without a concrete implementation. However, design patterns can help
de ne and develop frameworks. Mature frameworks usually reuse several design patterns. An im-
p ortant distinction b etween frameworks and design patterns is that frameworks are implemented
in a programming language. Our patterns are ways of using a programming language. In this sense
frameworks are more concrete than design patterns.
Design patterns are also related to the idioms intro duced by Coplien [7]. These idioms are concrete
++ ++
design solutions in the context of C . Coplien \fo cuses on idioms that makeC programs more
expressive." In contrast, design patterns are more abstract and higher-level than idioms. Patterns
try to abstract design rather than programming techniques. Moreover, design patterns are usually
indep endent of the implementation language.
There has b een interest recently within the ob ject-oriented community[8] in pattern languages
for the architecture of buildings and communities as advo cated by Christopher Alexander in The
Timeless Way of Building [2]. Alexander's patterns consist of three parts:
{ A context that describ es when a pattern is applicable.
{ The problem or \system of con icting forces" that the pattern resolves in that context.
{ A con guration that describ es physical relationships that solve the problem.
Both design patterns and Alexander's patterns share the notion of context/problem/con guration,
but our patterns currently do not form a complete system of patterns and so do not strictly de ne a
pattern language. This may b e b ecause ob ject-oriented design is still a young technology|wemay
not have had enough exp erience in what constitutes go o d design to extract design patterns that
cover all phases of the design pro cess. Or this may b e simply b ecause the problems encountered in
software design are di erent from those found in architecture and are not amenable to solution by
pattern languages.
Recently, Johnson has advo cated pattern languages to describ e how to use use ob ject-oriented
frameworks [16]. Johnson uses a pattern language to explain how to extend and customize the
Hotdraw drawing editor framework. However, these patterns are not design patterns; they are more
descriptions of how to reuse existing comp onents and frameworks instead of rules for generating new
designs.
Coad's recent pap er on ob ject-oriented patterns [6] is also motivated by Alexander's work but is
more closely related to our work. The pap er has seven patterns: \Broadcast" is the same as Observer,
but the other patterns are di erent from ours. In general, Coad's patterns seem to b e more closely
related to analysis than design. Design patterns likeWrapp er and Flyweight are unlikely to b e
generated naturally during analysis unless the analyst knows these patterns well and thinks in terms
of them. Coad's patterns could naturally arise from a simple attempt to mo del a problem. In fact,
it is hard to see howany large mo del could avoid using patterns like \State Across a Collection"
which explains how to use aggregation or \Behavior Across a Collection" which describ es howto
distribute resp onsibility among ob jects in an aggregate. The patterns in our catalog are typical of a
mature ob ject-oriented design, one that has departed from the original analysis mo del in an attempt
to make a system of reusable ob jects. In practice, b oth typ es of patterns are probably useful.
6 Conclusion
Design patterns have revolutionized the waywe think ab out, design, and teach ob ject-oriented
systems. Wehave found them applicable in many stages of the design pro cess|initial design, reuse,
refactoring. They have given us a new level of abstraction for system design.
New levels of abstraction often a ord opp ortunities for increased automation. We are investi-
gating howinteractive to ols can take advantage of design patterns. One of these to ols lets a user
explore the space of ob jects in a running program and watch their interaction. Through observation
the user may discover existing or entirely new patterns; the to ol lets the user record and catalog
his observations. The user maythus gain a b etter understanding of the application, the libraries on
which it is based, and design in general.
Design patterns mayhaveaneven more profound impact on how ob ject-oriented systems are
designed than wehave discussed. Common to most patterns is that they p ermit certain asp ects of
a system to b e varied indep endently. This leads to thinking ab out design in terms of \What asp ect
of a design should b e variable?" Answers to this question lead to certain applicable design patterns,
and their application leads subsequently to mo di cation of a design. We refer to this design activity
as variation-oriented design and discuss it more fully in the catalog of patterns [12].
But some caveats are in order. Design patterns should not b e applied indiscriminately. They
typically achieve exibility and variabilitybyintro ducing additional levels of indirection and can
therefore complicate a design. A design pattern should only b e applied when the exibility it a ords
is actually needed. The consequences describ ed in a pattern help determine this. Moreover, one is
often tempted to brand any new programming trick a new design pattern. A true design pattern
will b e non-trivial and will have had more than one application.
We hop e that the design patterns describ ed in this pap er and in the companion catalog will pro-
vide the ob ject-oriented community b oth a common design terminology and a rep ertoire of reusable
designs. Moreover, we hop e the catalog will motivate others to describ e their systems in terms of
design patterns and develop their own design patterns for others to reuse.
7 Acknowledgements
The authors wish to thank Doug Lea and Kent Beck for detailed comments and discussions ab out
this work, and Bruce Anderson and the participants of the Architecture Handb o ok workshops at
OOPSLA '91 and '92.
References
1. B. Adelson and Soloway E. The role of domain exp erience in software design. IEEE Transactions on
Software Engineering, 1111:1351{1360, 1985.
2. Christopher Alexander. The Timeless Way of Building. Oxford University Press, New York, 1979.
3. Asso ciation for Computing Machinery. Addendum to the Proceedings, Object-OrientedProgramming
Systems, Languages, and Applications Conference, Pho enix, AZ, Octob er 1991.
4. Asso ciation for Computing Machinery. Addendum to the Proceedings, Object-OrientedProgramming
Systems, Languages, and Applications Conference,Vancouver, British Columbia, Octob er 1992.
5. Kent Beck and Ward Cunningham. A lab oratory for teaching ob ject-oriented thinking. In Object-
OrientedProgramming Systems, Languages, and Applications ConferenceProceedings, pages 1{6, New
Orleans, LA, Octob er 1989.
6. Peter Coad. Ob ject-oriented patterns. Communications of the ACM, 359:152{159, Septemb er 1992.
7. James O. Coplien. Advanced C++ Programming Styles and Idioms. Addison-Wesley, Reading,
Massechusetts, 1992.
8. Ward Cunningham and Kent Beck. Constructing abstractions for ob ject-oriented applicatio ns. Technical
Rep ort CR-87{25, Computer Research Lab oratory,Tektronix, Inc., 1987.
9. Bill Curtis. Cognitive issues in reusing software artifacts. In Ted J. Biggersta and Alan J. Perlis,
editors, SoftwareReusability, Volume II, pages 269{287. Addison-Wesley, 1989.
10. Thomas Eggenschwiler and Erich Gamma. The ET++SwapsManager: Using ob ject technology in the
nancial engineering domain. In Object-OrientedProgramming Systems, Languages, and Applications
ConferenceProceedings, pages 166{178, Vancouver, British Columbia, Octob er 1992.
11. Erich Gamma. Objektorientierte Software-Entwicklung am Beispiel von ET++: Design-Muster, Klassen-
bibliothek, Werkzeuge. Springer-Verlag, Berlin, 1992.
12. Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. A catalog of ob ject-oriented design
patterns. Technical Rep ort in preparation, IBM Research Division , 1992.
13. Mehdi T. Harandi and Frank H. Young. Software design using reusable algorithm abstraction. In In
Proc. 2nd IEEE/BCS Conf. on Software Engineering, pages 94{97, 1985.
14. Richard Helm, Tien Huynh, Catherine Lassez, and Kim Marriott. A linear constraint technology for
user interfaces. In Graphics Interface, pages 301{309, Vancouver, British Columbia, 1992.
15. Richard Helm, Tien Huynh, Kim Marriott, and John Vlissides. An ob ject-oriented architecture for
constraint-based graphical editing. In Proceedings of the Third Eurographics Workshop on Object-
OrientedGraphics, pages 1{22, Champ ery, Switzerland, Octob er 1992. Also available as IBM Research
Division Technical Rep ort RC 18524 79392.
16. Ralph Johnson. Do cumenting frameworks using patterns. In Object-OrientedProgramming Systems,
Languages, and Applications ConferenceProceedings, pages 63{76, Vancouver, BC, Octob er 1992.
17. Ralph E. Johnson, Carl McConnell, and J. Michael Lake. The RTL system: A framework for co de
optimization. In Rob ert Giegerich and Susan L. Graham, editors, Code Generation|Concepts, Tools,
Techniques. Proceedings of the International Workshop on Code Generation, pages 255{274, Dagstuhl,
Germany, 1992. Springer-Verlag.
18. S. Katz, C.A. Richter, and K.-S. The. Paris: A system for reusing partially interpreted schemas. In
Proc. of the Ninth International Conference on Software Engineering, 1987.
19. Glenn E. Krasner and Stephen T. Pop e. A co okb o ok for using the mo del-view controller user interface
paradigm in Smalltalk-80. Journal of Object-OrientedProgramming, 13:26{49, August/September
1988.
20. Charles W. Krueger. Software reuse. ACM Computing Surveys, 242, June 1992.
21. Mark A. Linton. Encapsulating a C++ library.InProceedings of the 1992 USENIX C++ Conference,
pages 57{66, Portland, OR, August 1992.
22. Mark A. Linton, John M. Vlissides, and Paul R. Calder. Comp osing user interfaces with InterViews.
Computer, 222:8{22, February 1989.
23. William F. Op dyke and Ralph E. Johnson. Refactoring: An aid in designing application frameworks and
evolving ob ject-oriented systems. In SOOPPA ConferenceProceedings, pages 145{161, Marist College,
Poughkeepsie, NY, Septemb er 1990.
24. Charles Rich and Richard C. Waters. Formalizing reusable software comp onents in the programmer's
apprentice. In Ted J. Biggersta and Alan J. Perlis, editors, SoftwareReusability, Volume II, pages
313{343. Addison-Wesley, 1989.
25. James Rumbaugh, Michael Blaha, William Premerlani, Frederick Eddy, and William Lorenson. Object-
OrientedModeling and Design. Prentice Hall, Englewo o d Cli s, New Jersey, 1991.
26. Elliot Soloway and Kate Ehrlich. Empirical studies of programming knowledge. IEEE Transactions on
Software Engineering, 105, Septemb er 1984.
27. James C. Sp ohrer and Elliot Soloway.Novice mistakes: Are the folk wisdoms correct? Communications
of the ACM, 297:624{632, July 1992.
28. ParcPlace Systems. ParcPlace Systems, Objectworks/Smal ltalk Release 4 Users Guide. Mountain View,
California, 1990.
29. David Ungar and Randall B. Smith. Self: The p ower of simplici ty.InObject-OrientedProgramming
Systems, Languages, and Applications ConferenceProceedings, pages 227{242, Orlando, Florida, Octob er
1987.
30. John M. Vlissides and Mark A. Linton. Unidraw: A framework for buildin g domain-sp eci c graphical
editors. ACM Transactions on Information Systems, 83:237{268, July 1990.
31. Andr eWeinand, Erich Gamma, and Rudolf Marty. ET++|An ob ject-oriented application framework in
C++. In Object-OrientedProgramming Systems, Languages, and Applications ConferenceProceedings,
pages 46{57, San Diego, CA, Septemb er 1988.
32. Reb ecca Wirfs-Bro ck and Ralph E. Johnson. A survey of current research in ob ject-oriented design.
Communications of the ACM, 339:104{124, 1990.
A Catalog Overview
The following summarizes the patterns in our current catalog.
Abstract Factory provides an interface for creating generic pro duct ob jects. It removes dep endencies on
concrete pro duct classes from clients that create pro duct ob jects.
Adapter makes the proto col of one class conform to the proto col of another.
Bridge separates an abstraction from its implementation. The abstraction mayvary its implementations
transparently and dynamicall y.
Builder provides a generic interface for incrementally constructing aggregate ob jects. A Builder hides
details of how ob jects in the aggregate are created, represented, and comp osed.
Command ob jecti es the request for a service. It decouples the creator of the request for a service from
the executor of that service.
Comp osite treats multiple, recursively-comp osed ob jects as a single ob ject.
Chain of Resp onsibility de nes a hierarchy of ob jects, typically arranged from more sp eci c to more
general, having resp onsibil i ty for handling a request.
Factory Metho d lets base classes create instances of sub class-dep en dent ob jects.
Flyweight de nes how ob jects can b e shared. Flyweights supp ort ob ject abstraction at the nest granu-
larity.
Glue de nes a single p oint of access to ob jects in a subsystem. It provides a higher level of encapsulation
for ob jects in the subsystem.
Interpreter de nes how to represent the grammar, abstract syntax tree, and interpreter for simple lan-
guages.
Iterator ob jecti es traversal algorithms over ob ject structures.
Mediator decouples and manages the collab oration b etween ob jects.
Memento opaquely encapsulates a snapshot of the internal state of an ob ject and is used to restore the
ob ject to its original state.
Observer enforces synchronization, co ordination, and consistency constraints b etween ob jects.
Prototyp e creates new ob jects by cloning a prototypical instance. Prototyp es p ermit clients to install and
con gure dynamically the instances of particular classes they need to instantiate.
Proxy acts as a convenient surrogate or placeholder for another ob ject. Proxies can restrict, enhance, or
alter an ob ject's prop erties.
Solitaire de nes a one-of-a-kind ob ject that provides access to unique or well-known services and variables.
State lets an ob ject change its b ehavior when its internal state changes, e ectively changing its class.
Strategy ob jecti es an algorithm or b ehavior.
Template Metho d implements an abstract algorithm, deferring sp eci c steps to sub class metho ds.
Walker centralizes op erations on ob ject structures in one class so that these op erations can b e changed
indep endently of the classes de ning the structure.
Wrapp er attaches additional services, prop erties, or b ehavior to ob jects. Wrapp ers can b e nested recur-
sively to attachmultiple prop erties to ob jects.
Abstract Factory Ob ject Creational
Intent
Abstract Factory provides an interface for creating generic pro duct ob jects. It removes dep endencies
on concrete pro duct classes from clients that create pro duct ob jects.
Motivation
Consider a user interface to olkit that supp orts multiple standard lo ok-and-feels, say, Motif and Op en
Lo ok, and provides di erent scroll bars for each. It is undesirable to hard-co de dep endencies on either
standard into the application| the choice of lo ok-and-feel and hence scroll bar may b e deferred until
run-time. Sp ecifying the class of scroll bar limits exibili ty and reusabilityby forcing a commitmentto
a particular class instead of a particular proto col. An Abstract Factory avoids this commitment.
An abstract base class WindowKit declares services for creating scroll bars and other controls. Controls
for Motif and Op en Lo ok are derived from common abstract classes. For each lo ok-and-feel there is a
concrete sub class of WindowKit that de nes services to create the appropriate control. For example,
the CreateScrollBar op eration on the MotifKit would instantiate and return a Motif scroll bar, while
the corresp onding op eration on the Op enLo okKit returns an Op en Lo ok scroll bar. Clients access a
sp eci c kit through the interface declared by the WindowKit class, and they access the controls created
by a kit only by their generic interface.
WindowKit Window ScrollBar CreateScrollBar() CreateWIndow()
MotifWindow OpenLookWindow MotifScrollbar OpenLookScrollbar
MotifWindowKit OpenLookWindowKit CreateScrollBar() CreateScrollBar() return new OpenLookScrollBar CreateWindow() CreateWindow()
return
new MotifWindow
Applicability
When the classes of the pro duct ob jects are variable, and dep endencies on these classes must b e removed
from a client application.
When variations on the creation, comp osition, or representation of aggregate ob jects or subsystems must
b e removed from a client application. Di erences in con guration can b e obtained by using di erent
concrete factories. Clients do not explicitl y create and con gure the aggregate or subsystem but defer
this resp onsibili ty to an AbstractFactory class. Clients instead call a metho d of the AbstractFactory
that returns an ob ject providing access to the aggregate or subsystem.
Participants
AbstractFactory
{ declares a generic interface for op erations that create generic pro duct ob jects.
ConcreteFactory
{ de nes the op erations that create sp eci c pro duct ob jects.
GenericPro duct
{ declares a generic interface for pro duct ob jects.
Sp eci cPro duct
{ de nes a pro duct ob ject created by the corresp onding concrete factory.
{ all pro duct classes must conform to the generic pro duct interface.
Collab orations
Usually a single instance of a ConcreteFactory class is created at run-time. This concrete factory
creates pro duct ob jects having a particular implementation. To use di erent pro duct ob jects, clients
must b e con gured to use a di erent concrete factory.
AbstractFactory defers creation of pro duct ob jects to its ConcreteFactory sub classes. Diagram
AbstractFactory GenericProductA GenericProductB
MakeProductA() MakeProductB()
ProductA1 ProductA2 ProductB1 ProductB2
ConcreteFactory1 ConcreteFactory2 CreateFont return MakeProductA() MakeProductA() new ProductA2 MakeProductB() MakeProductB()
return
new ProductA1
Consequences
Abstract Factory provides a fo cus during development for changing and controlling the typ es of ob jects
created by clients. Because a factory ob jecti es the resp onsibili ty for and the pro cess of creating pro d-
uct ob jects, it isolates clients from implementation classes. Only generic interfaces are visible to clients.
Implementation class names do not app ear in client co de. Clients can b e de ned and implemented solely
in terms of proto cols instead of classes.
Abstract factories that enco de class names in op eration signatures can b e dicult to extend with new
kinds of pro duct ob jects. This can require redeclaring the AbstractFactory and all ConcreteFactories.
Abstract factories can b e comp osed with sub ordinate factory ob jects. Resp onsibil ity for creating ob jects
is delegated to these sub-factories. Comp osition of abstract factories provides a simple way to extend
the kinds of ob jects a factory is resp onsible for creating.
Examples
InterViews uses the \Kit" sux [21 ] to denote abstract factory classes. It de nes WidgetKit and Di-
alogKit abstract factories for generating lo ok-and-feel-sp eci c user interface ob jects. InterViews also
includes a LayoutKit that generates di erent comp osition ob jects dep ending on the layout desired.
ET++ [31 ] employs the Abstract Factory pattern to achieve p ortability across di erent window systems
X Windows and SunView, for example. The WindowSystem abstract base class de nes the interface for
creating ob jects representing window system resources for example, MakeWindow, MakeFont, Make-
Color. Concrete sub classes implement the interfaces for a sp eci c window system. At run-time ET++
creates an instance of a concrete WindowSystem sub class that creates system resource ob jects.
Implementation
Anovel implementation is p ossible in Smalltalk. Because classes are rst-class ob jects, it is not nec-
essary to have distinct ConcreteFactory sub classes to create the variations in pro ducts. Instead, it is
p ossible to store classes that create these pro ducts in variables inside a concrete factory. These classes
create new instances on b ehalf of the concrete factory. This technique p ermits variation in pro duct
ob jects at ner levels of granularity than by using distinct concrete factories. Only the classes kept in
variables need to b e changed.
See Also
Factory Metho d: Abstract Factories are often implemented using Factory Metho ds.
Strategy Ob ject Behavioral
Intent
A Strategy ob jecti es an algorithm or b ehavior, allowing the algorithm or b ehavior to b e varied inde-
p endently of its clients.
Motivation
There are many algorithms for breaking a text stream into lines. It is imp ossible to hard-wire all such
algorithms into the classes that require them. Di erent algorithms might b e appropriate at di erent
times.
One way to address this problem is by de ning separate classes that encapsulate the di erent linebreak-
ing algorithms. An algorithm ob jecti ed in this way is called a Strategy.InterViews [22] and ET++ [31]
use this approach.
Supp ose a Comp osition class is resp onsible for maintaining and up dating the line breaks of text displayed
in a text viewer. Linebreaking strategies are not implemented by the class Comp osition. Instead, they
are implemented separately by sub classes of the Comp ositor class. Comp ositor sub classes implement
di erent strategies as follows:
{ SimpleComp ositor implements a simple strategy that determines line breaks one at a time.
{TeXComp ositor implements the T Xalgorithm for nding line breaks. This strategy tries to
E
optimize line breaks globally, that is, one paragraph at a time.
{ ArrayComp ositor implements a strategy that is used not for text but for breaking a collection
of icons into rows. It selects breaks so that eachrow has a xed numb er of items.
A Comp osition maintains a reference to a Comp ositor ob ject. Whenever a Comp osition is required to
nd line breaks, it forwards this resp onsibil i ty to its current Comp ositor ob ject. The client of Comp o-
sition sp eci es which Comp ositor should b e used by installing the corresp onding Comp ositor into the
Comp osition see the diagram b elow.
Applicability
Whenever an algorithm or b ehavior should b e selectable and replaceable at run-time, or when there
exist variations in the implementation of the algorithm, re ecting di erent space-time tradeo s, for
example.
Use a Strategy whenever many related classes di er only in their b ehavior. Strategies provide a wayto
con gure a single class with one of many b ehaviors.
Participants
Strategy
{ ob jecti es and encapsulates an algorithm or b ehavior.
StrategyContext
{ maintains a reference to a Strategy ob ject.
{ maintains the state manipulated by the Strategy.
{ can b e con gured by passing it an appropriate Strategy ob ject.
Collab orations
Strategy manipulates the StrategyContext. The StrategyContext normally passes itself as an ar-
gument to the Strategy's metho ds. This allows the Strategy to call back the StrategyContext as
required.
StrategyContext forwards requests from its clients to the Strategy. Usually clients pass Strategy
ob jects to the StrategyContext. Thereafter clients only interact with the StrategyContext. There is
often a family of Strategy classes from which a client can cho ose. Diagram
strategy context
Composition
Repair() count = compositor−>Compose(breaks) Pick()
breaks compositor
strategies
Compositor
Compose() composition
ArrayCompositor TeXCompositor SimpleCompositor
Compose() Compose() Compose()
Consequences
Strategies can de ne a family of p olicies that a StrategyContext can reuse. Separating a Strategy
from its context increases reusability, b ecause the Strategy mayvary indep endently from the Strategy-
Context.
Variations on an algorithm can also b e implemented with inheritance, that is, with an abstract class
and sub classes that implement di erent b ehaviors. However, this hard-wires the implementation into a
sp eci c class; it is not p ossible to change b ehaviors dynamicall y. This results in many related classes that
di er only in some b ehavior. It is often b etter to break out the variations of b ehavior into their own
classes. The Strategy pattern thus increases mo dularityby lo calizing complex b ehavior. The typical
alternative is to scatter conditional statements throughout the co de that select the b ehavior to b e
p erformed.
Implementation
The interface of a Strategy and the common functionali ty among Strategies is often factored out in
an abstract class. Strategies should avoid maintaining state across invo cations so that they can b e used
rep eatedly and in multiple contexts.
Examples
In the RTL System for compiler co de optimization [17], Strategies de ne di erent register allo cation
schemes RegisterAllo cator and di erent instruction set scheduling p olicies RISCscheduler, CISC-
scheduler. This gives exibility in targeting the optimizer for di erent machine architectures.
The ET++SwapsManager calculation engine framework [10] computes prices for di erent nancial in-
struments. Its key abstractions are Instrument and YieldCurve. Di erent instruments are implemented
as sub classes of Instrument. The YieldCurve calculates discount factors to presentvalue future cash
ows. Both of these classes delegate some b ehavior to Strategy ob jects. The framework provides a fam-
ily of Strategy classes that de ne algorithms to generate cash ows, to value swaps, and to calculate
discount factors. New calculation engines are created by parameterizing Instrument and YieldCurve
with appropriate Strategy ob jects. This approach supp orts mixing and matching existing Strategy
implementation s while p ermitting the de nition of new Strategy ob jects.
See Also
Walker often implements algorithms over recursive ob ject structures. Walkers can b e considered com- p ound strategies.
Wrapper Comp ound Structural
Intent
AWrapp er attaches additional services, prop erties, or b ehavior to ob jects. Wrapp ers can b e nested
recursively to attachmultiple prop erties to ob jects.
Motivation
Sometimes it is desirable to attach prop erties to individua l ob jects instead of classes. In a graphi-
cal user interface to olkit, for example, prop erties such as b orders or services like scrolling should b e
freely attachable to any user interface comp onent.
One way to attach prop erties to comp onents is via inheritance. Inheriting a b order from a base class
will give all instances of its derived classes a b order. This is in exibl e b ecause the choice of b order is
made statically. It is more exible to let a client decide how and when to decorate the comp onent with
a b order.
This can b e achieved by enclosing the comp onent in another ob ject that adds the b order. The enclosing
ob ject, whichmust b e transparent to clients of the comp onent, is called a Wrapp er. This transparency
is the key for nesting Wrapp ers recursively to construct more complex user interface comp onents.
AWrapp er forwards requests to its enclosed user interface comp onent. The Wrapp er may p erform
additional actions b efore or after forwarding the request, suchasdrawing a b order around a user
interface comp onent.
Typical prop erties or services provided by user interface Wrapp ers are:
{ decorations like b orders, shadows, or scroll bars; or
{ services like scrolling or zo oming.
The following diagram illustrates the comp osition of a TextView with a BorderWrapp er and a Scroll-
Wrapp er to pro duce a b ordered, scrollable TextView.
(BorderWrapper) component (ScrollWrapper)
component (TextView)
Applicability
When prop erties or b ehaviors should b e attachable to individ ual ob jects dynamically and transpar-
ently.
When there is a need to extend classes in an inheritance hierarchy. Rather than mo difying their base
class, instances are enclosed in a Wrapp er that adds the additional b ehavior and prop erties. Wrapp ers
thus provide an alternative to extending the base class without requiring its mo di cation. This is of
particular concern when the base class comes from a class library that cannot b e mo di ed.
Participants
Comp onent
{ the ob ject to which additional prop erties or b ehaviors are attached.
Wrapp er
{ encapsulates and enhances its Comp onent. It de nes an interface that conforms to its Comp o-
nent's.
{Wrapp er maintains a reference to its Comp onent.
Collab orations
Wrapp er forwards requests to its Comp onent. It may optionall y p erform additional op erations b efore
and after forwarding the request. Diagram
VisualComponent Draw()
component Button BorderWrapper Draw() Draw() draw Border; component−>Draw()
borderWidth
Consequences
Using Wrapp ers to add prop erties is more exible than using inheritance. With Wrapp ers, prop er-
ties can b e attached and detached at run-time simply bychanging the Wrapp er. Inheritance would
require creating a new class for each prop erty comp osition for example, BorderdScrollab leTextVi ew,
BorderedTextView. This clutters the name space of classes unnecessarily and should b e avoided. More-
over, providing di erentWrapp er classes for a sp eci c Comp onent class allows mixing and matching
b ehaviors and prop erties.
Examples
Most ob ject-oriented user interface to olkits use Wrapp ers to add graphical emb ellishments to widgets.
Examples include InterViews [22], ET++ [31], and the ParcPlace Smalltalk class library [28]. More ex-
otic application s of Wrapp ers are the DebuggingGlyp h from InterViews and the PassivityWrapp er from
ParcPlace Smalltalk. A DebuggingGly ph prints out debugging information b efore and after it forwards
alayout request to its enclosed ob ject. This trace information can b e used to analyze and debug the
layout b ehavior of ob jects in a complex ob ject comp osition. The PassivityWrapp er can enable or disable
user interactions with the enclosed ob ject.
Implementation
Implementation of a set of Wrapp er classes is simpli ed by an abstract base class, which forwards
all requests to its comp onent. Derived classes can then override only those op erations for which they
want to add b ehavior. The abstract base class ensures that all other requests are passed automatically
to the Comp onent.
See Also
Adapter: A Wrapp er is di erent from an Adapter, b ecause a Wrapp er only changes an ob ject's prop er-
ties and not its interface; an Adapter will give an ob ject a completely new interface.
Comp osite: A Wrapp er can b e considered a degenerate Comp osite with only one comp onent. However,
aWrapp er adds additional services|it is not intented for ob ject aggregation.
a
This article was pro cessed using the L T X macro package with LLNCS style E