design_patterns.pdf
(
888 KB
)
Pobierz
72993717 UNPDF
tech facts at your fingertips
CONTENTS INCLUDE:
n
Chain of Responsibility
n
Command
n
Interpreter
n
Iterator
n
Mediator
n
Observer
n
Template Method and more...
Design
Patterns
By Jason McDonald
ABOUT DESIGN PATTERNS
Example
Exception handling in some languages implements this pattern.
When an exception is thrown in a method the runtime checks to
see if the method has a mechanism to handle the exception or
if it should be passed up the call stack. When passed up the call
stack the process repeats until code to handle the exception is
encountered or until there are no more parent objects to hand
the request to.
This Design Patterns refcard provides a quick reference to
the original 23 Gang of Four design patterns, as listed in the
book
Design Patterns: Elements of Reusable Object-Oriented
Software
.
Each pattern includes class diagrams, explanation,
usage information, and a real world example.
Creational Patterns:
Used to construct objects such that
they can be decoupled from their implementing system.
Structural Patterns:
Used to form large object structures
between many disparate objects.
Behavioral Patterns:
Used to manage algorithms,
relationships, and responsibilities between objects.
COMMAND
Object Behavioral
Client
Invoker
ConcreteCommand
+execute( )
Object Scope:
Deals with object relationships that can be
changed at runtime.
Class Scope:
Deals with class relationships that can be changed
at compile time.
Receiver
Command
+execute()
Purpose
Encapsulates a request allowing it to be treated as an object.
This allows the request to be handled in traditionally object
based relationships such as queuing and callbacks.
Use When
n
You need callback functionality.
n
Requests need to be handled at variant times or in variant orders.
n
A history of requests is needed.
n
The invoker should be decoupled from the object handling the
invocation.
Example
Job queues are widely used to facilitate the asynchronous
processing of algorithms. By utilizing the command pattern the
functionality to be executed can be given to a job queue for
processing without any need for the queue to have knowledge
of the actual implementation it is invoking. The command object
that is enqueued implements its particular algorithm within the
conines of the interface the queue is expecting.
C
Abstract Factory
S
Adapter
S
Bridge
C
Builder
B
Chain of
S
Decorator
S
Facade
C
Factory Method
S
Flyweight
B
Interpreter
B
Iterator
B
Mediator
B
Memento
C
Prototype
S
Proxy
B
Observer
C
Singleton
B
State
B
Strategy
B
Template Method
B
Visitor
Responsibility
B
Command
S
Composite
CHAIN OF RESPONSIBILITY
Object Behavioral
successor
Client
<<interface>>
Handler
+handlerequest()
ConcreteHandler 1
+handlerequest()
ConcreteHandler 2
+handlerequest()
Get
More
Refcardz
(
They’re free!
)
n
Authoritative content
n
Designed for developers
n
Written by top experts
n
Latest tools & technologies
n
Hot tips & examples
n
Bonus content online
n
New issue every 1-2 weeks
Purpose
Gives more than one object an opportunity to handle a request
by linking receiving objects together.
Use When
n
Multiple objects may handle a request and the handler
doesn’t have to be a speciic object.
n
A set of objects should be able to handle a request with the
handler determined at runtime.
n
A request not being handled is an acceptable potential
outcome.
Subscribe Now for FREE!
R
efcardz.com
DZone, Inc.
|
www.dzone.com
2
Design
Patterns
tech facts at your fingertips
INTERPRETER
Class Behavioral
MEDIATOR
Object Behavioral
Client
informs
Mediator
<<interface>>
Colleague
<<interface>>
AbstractExpression
+interpret()
Context
◆
TerminalExpression
+interpret
(
)
:
Context
NonterminalExpression
+interpret( ) : Context
ConcreteMediator
updates
ConcreteColleague
Purpose
Deines a representation for a grammar as well as a mechanism
to understand and act upon the grammar.
Use When
n
There is grammar to interpret that can be represented as
large syntax trees.
n
The grammar is simple.
n
Eficiency is not important.
n
Decoupling grammar from underlying expressions is desired.
Example
Text based adventures, wildly popular in the 1980’s, provide
a good example of this. Many had simple commands, such
as “step down” that allowed traversal of the game. These
commands could be nested such that it altered their meaning.
For example, “go in” would result in a different outcome than
“go up”. By creating a hierarchy of commands based upon
the command and the qualiier (non-terminal and terminal
expressions) the application could easily map many command
variations to a relating tree of actions.
Purpose
Allows loose coupling by encapsulating the way disparate sets of
objects interact and communicate with each other. Allows for the
actions of each object set to vary independently of one another.
Use When
n
Communication between sets of objects is well deined
and complex.
n
Too many relationships exist and common point of control
or communication is needed.
Example
Mailing list software keeps track of who is signed up to the
mailing list and provides a single point of access through which
any one person can communicate with the entire list. Without
a mediator implementation a person wanting to send a mes-
sage to the group would have to constantly keep track of who
was signed up and who was not. By implementing the mediator
pattern the system is able to receive messages from any point
then determine which recipients to forward the message on to,
without the sender of the message having to be concerned with
the actual recipient list.
ITERATOR
Object Behavioral
MEMENTO
Object Behavioral
Client
<<interface>>
Aggregate
+createIterator( )
<<interface>>
Iterator
+next()
Caretaker
Memento
-state
Concrete Aggregate
+createIterator( ) : Context
ConcreteIterator
+next( ) : Context
Originator
-state
+setMemento(in m : Memento)
+createMemento( )
Purpose
Allows for access to the elements of an aggregate object
without allowing access to its underlying representation.
Use When
n
Access to elements is needed without access to the entire
representation.
n
Multiple or concurrent traversals of the elements are needed.
n
A uniform interface for traversal is needed.
n
Subtle differences exist between the implementation details
of various iterators.
Example
The Java implementation of the iterator pattern allows users to
traverse various types of data sets without worrying about the
underlying implementation of the collection. Since clients simply
interact with the iterator interface, collections are left to deine
the appropriate iterator for themselves. Some will allow full ac-
cess to the underlying data set while others may restrict certain
functionalities, such as removing items.
Purpose
Allows for capturing and externalizing an object’s internal
state so that it can be restored later, all without violating
encapsulation.
Use When
n
The internal state of an object must be saved and restored
at a later time.
n
Internal state cannot be exposed by interfaces without exposing
implementation.
n
Encapsulation boundaries must be preserved.
Example
Undo functionality can nicely be implemented using the
memento pattern. By serializing and deserializing the state of
an object before the change occurs we can preserve a snapshot
of it that can later be restored should the user choose to undo
the operation.
DZone, Inc.
|
www.dzone.com
3
Design
Patterns
tech facts at your fingertips
OBSERvER
Object Behavioral
STRATEGY
Object Behavioral
<<interface>>
Subject
+attach(in o : Observer)
+detach(in o : Observer)
+notify( )
Context
notifies
<<interface>>
Observer
+update( )
<<interface>>
Strategy
+execute( )
ConcreteSubject
-subjectState
observes
ConcreteObserver
-observerState
+update( )
ConcreteStrategyA
+execute( )
ConcreteStrategyB
+execute( )
Purpose
Lets one or more objects be notiied of state changes in other
objects within the system.
Use When
n
State changes in one or more objects should trigger behavior
in other objects
n
Broadcasting capabilities are required.
n
An understanding exists that objects will be blind to the
expense of notiication.
Example
This pattern can be found in almost every GUI environment.
When buttons, text, and other ields are placed in applications
the application typically registers as a listener for those controls.
When a user triggers an event, such as clicking a button, the
control iterates through its registered observers and sends a
notiication to each.
Purpose
Deines a set of encapsulated algorithms that can be swapped
to carry out a speciic behavior.
Use When
n
The only difference between many related classes is their
behavior.
n
Multiple versions or variations of an algorithm are required.
n
Algorithms access or utilize data that calling code shouldn’t
be exposed to.
n
The behavior of a class should be deined at runtime.
n
Conditional statements are complex and hard to maintain.
Example
When importing data into a new system different validation
algorithms may be run based on the data set. By coniguring the
import to utilize strategies the conditional logic to determine
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
Context
+request ( )
TEMPLATE METHOD
Class Behavioral
<<interface>>
State
+handle( )
AbstractClass
+templateMethod( )
#subMethod( )
ConcreteState 1
+handle( )
ConcreteState 2
+handle( )
ConcreteClass
+subMethod( )
Purpose
Identiies the framework of an algorithm, allowing implementing
classes to deine the actual behavior.
Use When
n
A single abstract implementation of an algorithm is needed.
n
Common behavior among subclasses should be localized to a
common class.
n
Parent classes should be able to uniformly invoke behavior in
their subclasses.
n
Most or all subclasses need to implement the behavior.
Example
A parent class, InstantMessage, will likely have all the methods
required to handle sending a message. However, the actual
serialization of the data to send may vary depending on the
implementation. A video message and a plain text message
will require different algorithms in order to serialize the data
correctly. Subclasses of InstantMessage can provide their
own implementation of the serialization method, allowing the
parent class to work with them without understanding their
implementation details.
Purpose
Ties object circumstances to its behavior, allowing the object
to behave in different ways based upon its internal state.
Use When
n
The behavior of an object should be inluenced by its state.
n
Complex conditions tie object behavior to its state.
n
Transitions between states need to be explicit.
Example
An email object can have various states, all of which will
change how the object handles different functions. If the state
is “not sent” then the call to send() is going to send the message
while a call to recallMessage() will either throw an error or do
nothing. However, if the state is “sent” then the call to send()
would either throw an error or do nothing while the call to
recallMessage() would attempt to send a recall notiication
to recipients. To avoid conditional statements in most or all
methods there would be multiple state objects that handle the
implementation with respect to their particular state. The calls
within the Email object would then be delegated down to the
appropriate state object for handling.
DZone, Inc.
|
www.dzone.com
4
Design
Patterns
tech facts at your fingertips
vISITOR
Object Behavioral
BRIDGE
Object Structural
<<interface>>
visitor
+visitElementA(in a : ConcreteElementA)
+visitElementB(in b : ConcreteElementB)
Client
Abstraction
+operation( )
<<interface>>
Implementor
+operationImp( )
<<interface>>
Element
+accept(in v : Visitor)
Concretevisitor
+visitElementA(in a : ConcreteElementA)
+visitElementB(in b : ConcreteElementB)
ConcreteImplementorA
+operationImp( )
ConcreteImplementorB
+operationImp( )
ConcreteElementA
+accept(in v : Visitor)
ConcreteElementB
+accept(in v : Visitor)
Purpose
Deines an abstract object structure independently of the
implementation object structure in order to limit coupling.
Use When
n
Abstractions and implementations should not be bound at
compile time.
n
Abstractions and implementations should be independently
extensible.
n
Changes in the implementation of an abstraction should
have no impact on clients.
n
Implementation details should be hidden from the client.
Example
The Java Virtual Machine (JVM) has its own native set of functions
that abstract the use of windowing, system logging, and byte
code execution but the actual implementation of these functions
is delegated to the operating system the JVM is running on.
When an application instructs the JVM to render a window it
delegates the rendering call to the concrete implementation
of the JVM that knows how to communicate with the operating
system in order to render the window.
Purpose
Allows for one or more operations to be applied to a set of objects
at runtime, decoupling the operations from the object structure.
Use When
n
An object structure must have many unrelated operations
performed upon it.
n
The object structure can’t change but operations performed
on it can.
n
Operations must be performed on the concrete classes of an
object structure.
n
Exposing internal state or operations of the object structure
is acceptable.
n
Operations should be able to operate on multiple object
structures that implement the same interface sets.
Example
Calculating taxes in different regions on sets of invoices would
require many different variations of calculation logic. Implementing
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-
culation code that can then apply the proper rates for the region.
Changing regions is as simple as substituting a different visitor.
COMPOSITE
Object Structural
<<interface>>
Component
children
ADAPTER
Class and Object Structural
+operation( )
+add(in c : Component)
+remove(in c : Component)
+getChild(in i : int)
<<interface>>
Adapter
+operation( )
Client
Component
+operation( )
+add(in c : Component)
+remove(in c : Component)
+getChild(in i : int)
ConcreteAdapter
-adaptee
+operation( )
Adaptee
+adaptedOperation( )
Leaf
+operation( )
Purpose
Facilitates the creation of object hierarchies where each object
can be treated independently or as a set of nested objects
through the same interface.
Use When
n
Hierarchical representations of objects are needed..
n
Objects and compositions of objects should be treated uniformly.
Example
Sometimes the information displayed in a shopping cart is the
product of a single item while other times it is an aggregation
of multiple items. By implementing items as composites we can
treat the aggregates and the items in the same way, allowing us
to simply iterate over the tree and invoke functionality on each
item. By calling the getCost() method on any given node we
would get the cost of that item plus the cost of all child items,
allowing items to be uniformly treated whether they were single
items or groups of items.
Purpose
Permits classes with disparate interfaces to work together by
creating a common object by which they may communicate
and interact.
Use When
n
A class to be used doesn’t meet interface requirements.
n
Complex conditions tie object behavior to its state.
n
Transitions between states need to be explicit.
Example
A billing application needs to interface with an HR application in
order to exchange employee data, however each has its own inter-
face and implementation for the Employee object. In addition, the
SSN is stored in different formats by each system. By creating an
adapter we can create a common interface between the two appli-
cations that allows them to communicate using their native objects
and is able to transform the SSN format in the process.
DZone, Inc.
|
www.dzone.com
5
Design
Patterns
tech facts at your fingertips
DECORATOR
Object Structural
FLYwEIGHT
Object Structural
<<interface>>
Component
+operation( )
ConcreteComponent
+operation( )
FlyweightFactory
+getFlyweight(in key)
<<interface>>
Flyweight
+operation( in extrinsicState)
Decorator
+operation( )
Client
ConcreteDecorator
-addedState
+operation( )
+addedBehavior( )
ConcreteFlyweight
-intrinsicState
+operation( in extrinsicState)
UnsharedConcreteFlyweight
-allState
+operation( in extrinsicState)
Purpose
Allows for the dynamic wrapping of objects in order to modify
their existing responsibilities and behaviors.
Use When
n
Object responsibilities and behaviors should be dynamically
modiiable.
n
Concrete implementations should be decoupled from
responsibilities and behaviors.
n
Subclassing to achieve modiication is impractical or impossible.
n
Speciic functionality should not reside high in the object hierarchy.
n
A lot of little objects surrounding a concrete implementation is
acceptable.
Example
Many businesses set up their mail systems to take advantage of
decorators. When messages are sent from someone in the company
to an external address the mail server decorates the original
message with copyright and conidentiality information. As long
as the message remains internal the information is not attached.
This decoration allows the message itself to remain unchanged
until a runtime decision is made to wrap the message with
additional information.
Purpose
Facilitates the reuse of many ine grained objects, making the
utilization of large numbers of objects more eficient.
Use When
n
Many like objects are used and storage cost is high.
n
The majority of each object’s state can be made extrinsic.
n
A few shared objects can replace many unshared ones.
n
The identity of each object does not matter.
Example
Systems that allow users to deine their own application lows
and layouts often have a need to keep track of large numbers of
ields, pages, and other items that are almost identical to each
other. By making these items into lyweights all instances of each
object can share the intrinsic state while keeping the extrinsic
state separate. The intrinsic state would store the shared properties,
such as how a textbox looks, how much data it can hold, and
what events it exposes. The extrinsic state would store the
unshared properties, such as where the item belongs, how to
react to a user click, and how to handle events.
PROXY
Object Structural
FACADE
Object Structural
Client
Facade
<<interface>>
Subject
+request( )
Complex System
RealSubject
+request( )
represents
Proxy
+request( )
Purpose
Supplies a single interface to a set of interfaces within a system.
Use When
n
A simple interface is needed to provide access to a complex
system.
n
There are many dependencies between system implementations
and clients.
n
Systems and subsystems should be layered.
Example
By exposing a set of functionalities through a web service
the client code needs to only worry about the simple interface
being exposed to them and not the complex relationships that
may or may not exist behind the web service layer. A single
web service call to update a system with new data may actually
involve communication with a number of databases and systems,
however this detail is hidden due to the implementation of the
façade pattern.
Purpose
Allows for object level access control by acting as a pass through
entity or a placeholder object.
Use When
n
The object being represented is external to the system.
n
Objects need to be created on demand.
n
Access control for the original object is required.
n
Added functionality is required when an object is accessed.
Example
Ledger applications often provide a way for users to reconcile
their bank statements with their ledger data on demand, automat-
ing much of the process. The actual operation of communicating
with a third party is a relatively expensive operation that should be
limited. By using a proxy to represent the communications object
we can limit the number of times or the intervals the communica-
tion is invoked. In addition, we can wrap the complex instantiation
of the communication object inside the proxy class, decoupling
calling code from the implementation details.
DZone, Inc.
|
www.dzone.com
Plik z chomika:
pucor
Inne pliki z tego folderu:
the_art_of_readable_code.pdf
(25472 KB)
Prentice.Hall.Clean.Code.A.Handbook.of.Agile.Software.Crafts.pdf
(3005 KB)
patterns-based_engineering.pdf
(7849 KB)
design_patterns.pdf
(888 KB)
D2.1-2.2_Appendix_B_v1.0_Public_Version.pdf
(546 KB)
Inne foldery tego chomika:
agile
business and IT management
emagazines
embedded
linux
Zgłoś jeśli
naruszono regulamin