software design design pattern basics. introduction to design patterns©2002, michael j. lutz2 what...

33
Software Design Design Pattern Basics

Upload: kory-dalton

Post on 26-Dec-2015

222 views

Category:

Documents


1 download

TRANSCRIPT

Software Design

Design Pattern Basics

Introduction to Design Patterns ©2002, Michael J. Lutz 2

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 elementsrecurring the problem must be common core solution only a template – the essencereuse tailor template to specific

problem‡ Alexander, et. al. A Pattern Language. Oxford University Press. 1977.

Introduction to Design Patterns ©2002, Michael J. Lutz 3

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 4

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 5

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 6

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 7

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 8

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 9

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 10

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.

Digression:Adapter as an Example Pattern

Introduction to Design Patterns ©2002, Michael J. Lutz 12

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 13

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 14

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 15

Class Adaptation (via Inheritance)

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)

AdaptedSet

add(Object e)del(Object e)int cardinality()contains(Object e)

insert(e) ;

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 ©2002, Michael J. Lutz 16

Object Adaptation (via Delegation)

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)

adaptee.insert(e);

adapteeAdaptedSet

add(Object e)del(Object e)int cardinality()contains(Object e)

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.

Introduction to Design Patterns ©2002, Michael J. Lutz 17

Variant: Adapt Multiple Versions of NewSet

Client

NewHashSet NewBitSet

OldSet

NewSetAdaptedSet

(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.

adaptee

Introduction to Design Patterns ©2002, Michael J. Lutz 18

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 19

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 20

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 21

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.

End Digression

Introduction to Design Patterns ©2002, Michael J. Lutz 23

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 24

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 25

Key Pattern Description Elements

• Name

• Problem Brief, abstract description. Includes design context.

Introduction to Design Patterns ©2002, Michael J. Lutz 26

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 27

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 28

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 29

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 30

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 (run-

time). 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 31

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 32

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 33

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)