Design Patterns Refcard PDF
Design Patterns Refcard PDF
com
CONTENTS INCLUDE:
Chain of Responsibility
Design Patterns
n
n
Command
n
Interpreter
n
Iterator
n
Mediator
n
Observer By Jason McDonald
n
Template Method and more...
Example
ABOUT DESIGN PATTERNS Exception handling in some languages implements this pattern.
When an exception is thrown in a method the runtime checks to
This Design Patterns refcard provides a quick reference to see if the method has a mechanism to handle the exception or
the original 23 Gang of Four design patterns, as listed in the if it should be passed up the call stack. When passed up the call
book Design Patterns: Elements of Reusable Object-Oriented stack the process repeats until code to handle the exception is
Software. Each pattern includes class diagrams, explanation, encountered or until there are no more parent objects to hand
usage information, and a real world example. the request to.
n Authoritative content
Purpose n Designed for developers
Gives more than one object an opportunity to handle a request n Written by top experts
request
add a header to the HTTP
Use When
setRequestHeader
(namevalue)
send the request
send(body) as request body
body = string to be used
for the response
stop the XHR from listening
abort()
(only populated after send()
stage in lifecycle of response
n
A set of objects should be able to handle a request with the
handler determined at runtime. Subscribe Now for FREE!
n
A request not being handled is an acceptable potential Refcardz.com
outcome.
Client informs
Mediator <<interface>>
Colleague
<<interface>>
Context AbstractExpression
+interpret( )
TerminalExpression NonterminalExpression updates
ConcreteMediator ConcreteColleague
+interpret( ) : Context +interpret( ) : Context
Purpose
Purpose
Allows loose coupling by encapsulating the way disparate sets of
Defines a representation for a grammar as well as a mechanism
objects interact and communicate with each other. Allows for the
to understand and act upon the grammar.
actions of each object set to vary independently of one another.
Use When
Use When
n
There is grammar to interpret that can be represented as n
Communication between sets of objects is well defined
large syntax trees.
and complex.
n
The grammar is simple. n
Too many relationships exist and common point of control
n
Efficiency is not important.
or communication is needed.
n
Decoupling grammar from underlying expressions is desired.
Example
Example
Mailing list software keeps track of who is signed up to the
Text based adventures, wildly popular in the 1980s, provide
mailing list and provides a single point of access through which
a good example of this. Many had simple commands, such
any one person can communicate with the entire list. Without
as step down that allowed traversal of the game. These
a mediator implementation a person wanting to send a mes-
commands could be nested such that it altered their meaning.
For example, go in would result in a different outcome than sage to the group would have to constantly keep track of who
go up. By creating a hierarchy of commands based upon was signed up and who was not. By implementing the mediator
the command and the qualifier (non-terminal and terminal pattern the system is able to receive messages from any point
expressions) the application could easily map many command then determine which recipients to forward the message on to,
variations to a relating tree of actions. without the sender of the message having to be concerned with
the actual recipient list.
Client
+createIterator( ) +next( )
<<interface>> Context
Subject
notifies <<interface>>
+attach(in o : Observer) Observer <<interface>>
+detach(in o : Observer) Strategy
+notify( ) +update( )
+execute( )
ConcreteStrategyA ConcreteStrategyB
ConcreteSubject ConcreteObserver
observes +execute( ) +execute( )
-subjectState -observerState
+update ( )
Purpose
Purpose Defines a set of encapsulated algorithms that can be swapped
Lets one or more objects be notified of state changes in other to carry out a specific behavior.
objects within the system.
Use When
Use When n
The only difference between many related classes is their
n
State changes in one or more objects should trigger behavior
behavior.
in other objects n
Multiple versions or variations of an algorithm are required.
n
Broadcasting capabilities are required. n
Algorithms access or utilize data that calling code shouldnt
n
An understanding exists that objects will be blind to the
be exposed to.
expense of notification. n
The behavior of a class should be defined at runtime.
Example n
Conditional statements are complex and hard to maintain.
This pattern can be found in almost every GUI environment.
Example
When buttons, text, and other fields are placed in applications
When importing data into a new system different validation
the application typically registers as a listener for those controls.
algorithms may be run based on the data set. By configuring the
When a user triggers an event, such as clicking a button, the
import to utilize strategies the conditional logic to determine
control iterates through its registered observers and sends a
notification to each. what validation set to run can be removed and the import can be
decoupled from the actual validation code. This will allow us to
dynamically call one or more strategies during the import.
STATE Object Behavioral
+request ( )
<<interface>> AbstractClass
State +templateMethod( )
+handle( ) #subMethod( )
ConcreteClass
ConcreteState 1 ConcreteState 2 +subMethod( )
+handle ( ) +handle ( )
Purpose
Purpose Identifies the framework of an algorithm, allowing implementing
Ties object circumstances to its behavior, allowing the object classes to define the actual behavior.
to behave in different ways based upon its internal state.
Use When
Use When n
A single abstract implementation of an algorithm is needed.
The behavior of an object should be influenced by its state.
n
n
Common behavior among subclasses should be localized to a
Complex conditions tie object behavior to its state.
n
common class.
Transitions between states need to be explicit.
n
n
Parent classes should be able to uniformly invoke behavior in
Example their subclasses.
An email object can have various states, all of which will n
Most or all subclasses need to implement the behavior.
change how the object handles different functions. If the state
Example
is not sent then the call to send() is going to send the message
A parent class, InstantMessage, will likely have all the methods
while a call to recallMessage() will either throw an error or do
nothing. However, if the state is sent then the call to send() required to handle sending a message. However, the actual
would either throw an error or do nothing while the call to serialization of the data to send may vary depending on the
recallMessage() would attempt to send a recall notification implementation. A video message and a plain text message
to recipients. To avoid conditional statements in most or all will require different algorithms in order to serialize the data
methods there would be multiple state objects that handle the correctly. Subclasses of InstantMessage can provide their
implementation with respect to their particular state. The calls own implementation of the serialization method, allowing the
within the Email object would then be delegated down to the parent class to work with them without understanding their
appropriate state object for handling. implementation details.
<<interface>> Abstraction
Visitor Client
+operation( )
<<interface>>
+visitElementA(in a : ConcreteElementA)
Implementor
+visitElementB(in b : ConcreteElementB)
<<interface>>
+operationImp( )
Element
ConcreteVisitor +accept(in v : Visitor)
+visitElementA(in a : ConcreteElementA) ConcreteImplementorA ConcreteImplementorB
+visitElementB(in b : ConcreteElementB)
+operationImp( ) +operationImp( )
ConcreteElementA
+accept(in v : Visitor)
ConcreteElementB Purpose
+accept(in v : Visitor) Defines an abstract object structure independently of the
implementation object structure in order to limit coupling.
Purpose
Allows for one or more operations to be applied to a set of objects Use When
at runtime, decoupling the operations from the object structure.
n
Abstractions and implementations should not be bound at
compile time.
Use When n
Abstractions and implementations should be independently
n
An object structure must have many unrelated operations extensible.
performed upon it. n
Changes in the implementation of an abstraction should
n
The object structure cant change but operations performed have no impact on clients.
on it can. n
Implementation details should be hidden from the client.
n
Operations must be performed on the concrete classes of an
Example
object structure.
The Java Virtual Machine (JVM) has its own native set of functions
n
Exposing internal state or operations of the object structure
that abstract the use of windowing, system logging, and byte
is acceptable. code execution but the actual implementation of these functions
n
Operations should be able to operate on multiple object is delegated to the operating system the JVM is running on.
structures that implement the same interface sets. When an application instructs the JVM to render a window it
Example delegates the rendering call to the concrete implementation
Calculating taxes in different regions on sets of invoices would of the JVM that knows how to communicate with the operating
require many different variations of calculation logic. Implementing system in order to render the window.
a visitor allows the logic to be decoupled from the invoices and
line items. This allows the hierarchy of items to be visited by cal-
COMPOSITE Object Structural
culation code that can then apply the proper rates for the region.
Changing regions is as simple as substituting a different visitor.
<<interface>>
Component
children
ADAPTER Class and Object Structural +operation( )
+add(in c : Component )
+remove(in c : Component )
+getChild(in i : int)
<<interface>>
Adapter
Client
+operation( ) Component
Leaf +operation( )
+operation( ) +add(in c : Component )
ConcreteAdapter +remove(in c : Component )
Adaptee
-adaptee +getChild(in i : int)
+operation( ) +adaptedOperation ( )
Purpose
Purpose Facilitates the creation of object hierarchies where each object
Permits classes with disparate interfaces to work together by can be treated independently or as a set of nested objects
creating a common object by which they may communicate through the same interface.
and interact. Use When
Use When Hierarchical representations of objects are needed..
n
+operation( ) +getFlyweight(in key)
+operation ( ) +operation( in extrinsicState)
Decorator Client
+operation( )
ConcreteDecorator ConcreteFlyweight
-addedState -intrinsicState UnsharedConcreteFlyweight
+operation ( ) +operation ( in extrinsicState) -allState
+addedBehavior ( ) +operation ( in extrinsicState)
Purpose Purpose
Allows for the dynamic wrapping of objects in order to modify Facilitates the reuse of many fine grained objects, making the
their existing responsibilities and behaviors. utilization of large numbers of objects more efficient.
n
Subclassing to achieve modification is impractical or impossible. Example
n
Specific functionality should not reside high in the object hierarchy. Systems that allow users to define their own application flows
n
A lot of little objects surrounding a concrete implementation is and layouts often have a need to keep track of large numbers of
acceptable. fields, pages, and other items that are almost identical to each
other. By making these items into flyweights all instances of each
Example
object can share the intrinsic state while keeping the extrinsic
Many businesses set up their mail systems to take advantage of
state separate. The intrinsic state would store the shared properties,
decorators. When messages are sent from someone in the company
such as how a textbox looks, how much data it can hold, and
to an external address the mail server decorates the original
what events it exposes. The extrinsic state would store the
message with copyright and confidentiality information. As long
unshared properties, such as where the item belongs, how to
as the message remains internal the information is not attached.
react to a user click, and how to handle events.
This decoration allows the message itself to remain unchanged
until a runtime decision is made to wrap the message with
additional information. PROXY Object Structural
<<interface>>
Subject
Facade
Complex System +request( )
Purpose
Allows for object level access control by acting as a pass through
Purpose
Supplies a single interface to a set of interfaces within a system. entity or a placeholder object.
n
There are many dependencies between system implementations Access control for the original object is required.
n
n
Systems and subsystems should be layered. Example
Example Ledger applications often provide a way for users to reconcile
By exposing a set of functionalities through a web service their bank statements with their ledger data on demand, automat-
the client code needs to only worry about the simple interface ing much of the process. The actual operation of communicating
being exposed to them and not the complex relationships that with a third party is a relatively expensive operation that should be
may or may not exist behind the web service layer. A single limited. By using a proxy to represent the communications object
web service call to update a system with new data may actually we can limit the number of times or the intervals the communica-
involve communication with a number of databases and systems, tion is invoked. In addition, we can wrap the complex instantiation
however this detail is hidden due to the implementation of the of the communication object inside the proxy class, decoupling
faade pattern. calling code from the implementation details.
Use When
Parent classes wish to defer creation to their subclasses.
n
n
The creation of objects should be independent of the system
utilizing them. Example
Many applications have some form of user and group structure
n
Systems should be capable of using multiple families of objects.
for security. When the application needs to create a user it will
n
Families of objects must be used together.
typically delegate the creation of the user to multiple user
n
Libraries must be published without exposing implementation
implementations. The parent user object will handle most
details.
operations for each user but the subclasses will define the factory
n
Concrete classes should be decoupled from clients.
method that handles the distinctions in the creation of each type
Example of user. A system may have AdminUser and StandardUser objects
Email editors will allow for editing in multiple formats including each of which extend the User object. The AdminUser object
plain text, rich text, and HTML. Depending on the format being may perform some extra tasks to ensure access while the
used, different objects will need to be created. If the message StandardUser may do the same to limit access.
is plain text then there could be a body object that represented
just plain text and an attachment object that simply encrypted
the attachment into Base64. If the message is HTML then the PROTOTYPE Object Creational
Director <<interface>>
Builder Purpose
+construct( )
+buildPart( ) Create objects based upon a template of an existing objects
through cloning.
ConcreteBuilder Use When
+buildPart( ) n
Composition, creation, and representation of objects should
+getResult( )
be decoupled from a system.
Purpose n
Classes to be created are specified at runtime.
Allows for the dynamic creation of objects based upon easily n
A limited number of state combinations exist in an object.
interchangeable algorithms. n
Objects or object structures are required that are identical or
Use When closely resemble other existing objects or object structures.
n
Object creation algorithms should be decoupled from the system. n
The initial creation of each object is an expensive operation.
n
Multiple representations of creation algorithms are required. Example
n
The addition of new creation functionality without changing Rates processing engines often require the lookup of many
the core code is necessary. different configuration values, making the initialization of the
n
Runtime control over the creation process is required. engine a relatively expensive process. When multiple instances
Example of the engine is needed, say for importing data in a multi-threaded
A file transfer application could possibly use many different manner, the expense of initializing many engines is high. By
protocols to send files and the actual transfer object that will be utilizing the prototype pattern we can ensure that only a single
created will be directly dependent on the chosen protocol. Using copy of the engine has to be initialized then simply clone the
a builder we can determine the right builder to use to instantiate engine to create a duplicate of the already initialized object.
the right object. If the setting is FTP then the FTP builder would The added benefit of this is that the clones can be streamlined
be used when creating the object. to only include relevant data for their situation.
Use When
SINGLETON Object Creational
Exactly one instance of a class is required.
n
Example
Singleton
Most languages provide some sort of system or environment
-static uniqueInstance object that allows the language to interact with the native operat-
-singletonData
ing system. Since the application is physically running on only one
+static instance( ) operating system there is only ever a need for a single instance of
+singletonOperation( )
this system object. The singleton pattern would be implemented
by the language runtime to ensure that only a single copy of the
Purpose system object is created and to ensure only appropriate processes
Ensures that only one instance of a class is allowed within a system. are allowed access to it.
DZone, Inc.
ISBN-13: 978-1-934238-10-3
1251 NW Maynard
ISBN-10: 1-934238-10-4
Cary, NC 27513
50795
888.678.0399
DZone communities deliver over 4 million pages each month to 919.678.0300
more than 1.7 million software developers, architects and decision Refcardz Feedback Welcome
refcardz@dzone.com
$7.95