Software Design
Design Pattern Basics
What Are Patterns?
Each pattern describes a problem which occurs over and over
again in our environment, and then describes the core of the
solution to that problem, in such a way that you can use this
solution a million times over, without ever doing it the same
way twice.
Christopher Alexander‡
Key elements
recurring
the problem must be common
core solution only a template – the essence
reuse
tailor template to specific problem
‡ Alexander, et. al. A Pattern Language. Oxford University Press. 1977.
Introduction to Design Patterns
©2002, Michael J. Lutz
2
Why Patterns?
• Design is a challenging task:
 Balancing concerns, e.g. performance, adaptability,
reliability.
 Defining components and their interrelationships.
• Thus experienced designers:
 Rarely start from first principles
 Look for similarities to problems solved in the past.
 Apply a working "handbook" of approaches
• Patterns make expert knowledge widely available
 Supports focusing on the truly distinctive design
problems.
 Aids design evaluation at higher level of abstraction
 Provides a useful working vocabulary for design.
Introduction to Design Patterns
©2002, Michael J. Lutz
3
Levels of Patterns
• Patterns occur at every level of development.
• Code level: Idioms
 Recurring control structure groupings.
 Example: sentinel terminated loop.
• System Level: Architectural styles
 Recurring system level structures.
 Example: layers (e.g., Internet protocols).
 Example: client/server (e.g., World Wide Web).
• Subsystem Level: Design patterns
 Recurring tactical structures.
 Example: iterators to process collections of objects.
 This level is the focus of these slides.
Introduction to Design Patterns
©2002, Michael J. Lutz
4
OO Design Problem Sampler - 1
Problem: Dependence on specific algorithms
 Different algorithms are appropriate in different
circumstances.
 Processing the items in a list is (slightly) different from
processing items in a hash table.
 Different algorithms (e.g., sorting) are appropriate for
different data sets.
Solution: Hide details behind an interface
 Clients get the most appropriate implementation.
 Client may make the choice and pass this on.
 Service may make the choice for the client.
Introduction to Design Patterns
©2002, Michael J. Lutz
5
Example Pattern - 1
Iterator
 Need to process all elements of a general collection.
 Collection structures differ, thus iteration algorithms differ.
 But iteration interface is fixed.
 Each collection produces an iterator with the appropriate
algorithm tied to the fixed iterator interface.
Introduction to Design Patterns
©2002, Michael J. Lutz
6
OO Design Problem Sampler - 2
Problem: Overly tight coupling
 Difficult to reuse or extend classes with high
interdependence.
 Makes extension, portability, etc., much harder.
Solution: Loosen the relationship among the classes
 Develop a simpler connection protocol .
 Centralize some of the interaction in a traffic manager.
Introduction to Design Patterns
©2002, Michael J. Lutz
7
Example Pattern - 2
Mediator
 Have an richly connected subsystem
– Example: Widgets on account setup dialog box in Outlook.
 Changes to one component affect many other
components:
– Selecting the “authorization required” control enables the account
name & password entry textboxes.
 Create a mediator object which knows how to synchronize
the subsystem components.
 All notifications go to the mediator.
 All changes initiated by the mediator.
Introduction to Design Patterns
©2002, Michael J. Lutz
8
OO Design Problem Sampler - 3
Problem: Inability to alter existing classes:
 Perhaps the source is unavailable.
 Need to alter the class to:
– Provide enhanced functionality.
– Use an interface consistent with the rest of the system.
Solution: Put another object in front:
 Enhance the operation in the front-end object; pass
through what you can.
 Convert calls on the desired interface to that of the
unchangeable object.
Introduction to Design Patterns
©2002, Michael J. Lutz
9
Example Pattern - 3
Adapter
 Have a class of objects with desired functionality but
wrong interface.
 Create an class with correct interface to “wrap” the
incompatible objects.
 Adapter converts / translates between the two interface
conventions.
The next few slides discuss adapter as an example of
applying a panel.
Introduction to Design Patterns
©2002, Michael J. Lutz
10
Digression:
Adapter as an Example Pattern
Adapter Description
Intent
 Convert the interface of a class to an interface expected
by the users of the class.
 Allows classes to work together even though they
expect incompatible interfaces.
Example (non-software)
 U.S. electrical system: 110 VAC @ 60 Hz.
 European electrical system: 220 VAC @ 50 Hz.
 How can we use U.S. appliances in Europe?
 Adapters!
Introduction to Design Patterns
©2002, Michael J. Lutz
12
Example – Sets
• There are many ways to implement a set
• Assume that:
 Existing systems based on sets from a local library.
 The local version is inadequate (e.g., poor performance).
• We acquire a better set class, BUT:
 The new set has a different interface.
 And we have no access to the source code!
• Solution: A class or object set adapter:
 Same interface as existing system’s expect.
 Simply translates to the new set’s interface.
Introduction to Design Patterns
©2002, Michael J. Lutz
13
Graphical Description
Client
OldSet
add(Object e)
del(Object e)
int cardinality()
contains(Object e)
NewSet
insert(Object e)
remove(Object e)
int size()
contains(Object e)
Introduction to Design Patterns
?
©2002, Michael J. Lutz
14
Class Adaptation (via Inheritance)
Client
With careful implementation,
the adapted set can appear to
be either an OldSet or a
NewSet
This approach works in
languages like Java only if the
OldSet is an interface, not a
class (because Java does not
support general multiple
inheritance).
Introduction to Design Patterns
OldSet
add(Object e)
del(Object e)
int cardinality()
contains(Object e)
NewSet
insert(Object e)
remove(Object e)
int size()
contains(Object e)
AdaptedSet
add(Object e)
del(Object e)
int cardinality()
contains(Object e)
©2002, Michael J. Lutz
insert(e) ;
15
Object Adaptation (via Delegation)
Client
Note that there are two
objects involved in the
adaptation.
The first object
implements the OldSet
interface. This object has
a reference to a NewSet
object that does the
actual work.
OldSet
add(Object e)
del(Object e)
int cardinality()
contains(Object e)
AdaptedSet
add(Object e)
del(Object e)
int cardinality()
contains(Object e)
Introduction to Design Patterns
©2002, Michael J. Lutz
NewSet
insert(Object e)
remove(Object e)
int size()
contains(Object e)
adaptee
adaptee.insert(e);
16
Variant: Adapt Multiple Versions of NewSet
(Object only) Several subclasses to adapt:
• Too expensive to adapt each subclass.
• Create single adapter to superclass interface.
• Configure the AdaptedSet with the specific NewSet
at run-time.
Client
OldSet
AdaptedSet
adaptee
NewSet
NewHashSet
Introduction to Design Patterns
©2002, Michael J. Lutz
NewBitSet
17
Consequences - Class Adapters
• Creates concrete adapter for a specific Adaptee
(e.g., NewSet)
• Cannot adapt a class and all its subclasses
• Only one object is created
 The object has two faces (or identities).
 But there is no need for indirection.
• Can override Adaptee (e.g., NewSet) behavior, as
Adapter is a subclass of Adaptee
Introduction to Design Patterns
©2002, Michael J. Lutz
18
Consequences - Object Adapters
• Single Adapter class handles many Adaptees
 Any class that has the specified Adaptee interface (e.g.,
all NewSets).
 Can adapt the Adaptee class and all its subclasses.
• Hard to override Adaptee behavior
 Because the Adapter uses but does not inherit from the
Adaptee interface.
 Overriding means:
– Subclassing Adaptee to modify behavior.
– Adapting the subclass.
– Often not be worth the effort.and adapt this.
Introduction to Design Patterns
©2002, Michael J. Lutz
19
Other Issues
• How much adapting does adapter do?
 Simple forwarding of requests (renaming)?
 Different set of operations & semantics?
 At what point do the Adaptee and Adapter interfaces
diverge so much that “adaption” is no longer the correct
term?
Introduction to Design Patterns
©2002, Michael J. Lutz
20
Implementation
• C++ Class Adapters
 public inheritance from Target class.
 private inheritance from Adaptee class.
 => Adapter of type Target but not Adaptee.
• Adapting to Java interfaces
 Similar to class adaptation via multiple inheritance.
 Lighter weight than class adapting.
 No carrying of useless superclass baggage.
Introduction to Design Patterns
©2002, Michael J. Lutz
21
End Digression
Keys to Using Patterns Effectively
• Recognize, search, instantiate:
 Recognize a problem as common (déjà vu).
 Recognize the key elements of the problem.
 Search a pattern catalog from proven solution
templates.
 Instantiate the template for the specific problem.
• Recognition comes with experience
• Searching is aided by a catalog taxonomy
• Instantiation requires tactical skill:
 Specific interface definition.
 Algorithm and data structure selection.
Introduction to Design Patterns
©2002, Michael J. Lutz
23
Key Pattern Description Elements
• Name
 A good, descriptive name is critical.
– Good names communicate.
– Poor names obfuscate.
 Goal: Increase design vocabulary.
 Goal: Raise level of design discussion.
Introduction to Design Patterns
©2002, Michael J. Lutz
24
Key Pattern Description Elements
• Name
• Problem
 Brief, abstract description.
 Includes design context.
Introduction to Design Patterns
©2002, Michael J. Lutz
25
Key Pattern Description Elements
• Name
• Problem
• Solution
 Components (classes/objects) and interconnections.
 Generic control and data flow supported by the pattern.
 Template, not a cookbook.
Introduction to Design Patterns
©2002, Michael J. Lutz
26
Key Pattern Description Elements
• Name
• Problem
• Solution
• Consequences & Tradeoffs
 Positive results.
 Negative implications.
 Tradeoffs: time, space, flexibility, performance, etc.
Introduction to Design Patterns
©2002, Michael J. Lutz
27
Key Pattern Description Elements
• Name
• Problem
• Solution
• Consequences & Tradeoffs
• Implementation issues
 Effects of language (i.e., Java vs. C++).
 Alternative tactical approaches.
Introduction to Design Patterns
©2002, Michael J. Lutz
28
Canonical Cataloging
Design Patterns by Gamma, Helm, Johnson, and Vlissides
 The first widely circulated pattern collection.
 This so-called “Gang of Four” (or GOF) provided the first
pattern taxonomy.
 Most other catalogs use a variant of GOF.
Introduction to Design Patterns
©2002, Michael J. Lutz
29
The Gang of Four Catalog Method
Pattern name and classification as key indices
 Purpose classification: creational, structural, behavioral.
 Scope classification: class (compile time) or object (runtime).
 Creational – when and how objects are instantiated:
– class => defer creation to subclasses
– object => defer creation to another object.
 Structural – how objects are composed into larger groups:
– class => structure via inheritance.
– object => structure via composition.
 Behavioral – how responsibilities are distributed:
– class => algorithms/control via inheritance.
– object => algorithms/control via object groups.
Introduction to Design Patterns
©2002, Michael J. Lutz
30
GOF Pattern Description - 1
Intent
 What issue/problem does the pattern address?
 What is its rationale?
Also Known As = other names for pattern
Motivation
 Scenario illustrating problem and solution.
 A concrete exemplar.
Applicability
 When to choose the pattern.
 Poor designs addressed by pattern.
Introduction to Design Patterns
©2002, Michael J. Lutz
31
Pattern Description - 2
• Structure
 Static: Class and object diagrams.
 Dynamic: Sequence diagrams.
• Participants
 Classes and/or objects.
 Roles and responsibilities.
• Collaborations
 Rules of participant interactions.
 Frequently these are constraints that are hard to diagram.
Introduction to Design Patterns
©2002, Michael J. Lutz
32
Pattern Description - 3
• Consequences
 How does pattern meet its objectives?
 Tradeoff analysis – what gets better, what may get worse.
 Flexibility: what parts can vary independently?
• Implementation & Sample Code
• Known Uses (to show pattern generality)
• Related Patterns (in case this isn’t quite right)
Introduction to Design Patterns
©2002, Michael J. Lutz
33
Descargar

Design Pattern Basics