1 introduction to design patterns. 2 outline introduction and background common and simple design...

102
1 Introduction to Design Patterns

Upload: jonas-lang

Post on 29-Dec-2015

214 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

1

Introduction to Design Patterns

Page 2: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

2

Outline

• Introduction and Background

• Common and Simple Design Patterns

• Identification and Application of Design Patterns

• Advanced Design Patterns

• Exercises

Page 3: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

3

Goal of Presentation

Provide a working introduction toPatternsPattern SystemsUsing pattern resources (web, books, etc.)Identifying and sharing domain specific patternsUse of patterns in Java

Page 4: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

4

Pattern Definition

A "pattern" is ...An abstraction from a concrete form which keeps recurring in specific, non-arbitrary contexts. [generic definition] A recurring solution to a common problem in a given context and system of forces. [Alexander] A named "nugget" of instructive insight, conveying the essence of a proven solution to a recurring problem in a given context amidst competing concerns. A successfully recurring "best practice" that has proven itself in the "trenches".

A literary format for capturing the wisdom and experience of expert designers, and communicating it to novices

Page 5: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

5

What are software patterns?Trendy:

Recent "hot-topic", OOD buzzword, lots of "hype"

Literary: Form of software engineering problem-solving documentation

Pragmatic:Describe practical solutions to "real world" problems

Recurring:Identify good design structures which recur in practice

Generative: Show how/when to apply the solution, and generate the desired design structure

Emergent:Larger solutions emerge indirectly from applying patterns in succession, and in concert together

Page 6: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

6

Example

Name: Singleton

Category: Object Creation

Intent:Ensure a class only has one instance and provide global point of access

Motivation:It’s important for some classes to have exactly one instance. For example, there typically is only one instance of each file system class in an operating system….

return unique Instance

Singleton

-uniqueInstancesingletonData

-Instance()SingletonOperation()GetSingletonData()

Page 7: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

7

Example Use of Singleton: Metadata

Metadata objects “Data that describes other data”Not of the same class as the objects they describe

Cake recipe is not a cake, but describes how to make

Form of object-based classification

Most OO languages have metadata “class” objects

What came first, the class or the object?

Used when there arePotentially an infinite number of types

Models of cars, recipes

Lots of component based semantic dependencies

Account types, calling plans

ExampleCatalog Entry is very different than Warehouse Item

but they have analogous structure (e.g. Relationship of parts)

Do not want to use inheritance to model analogies

Problems when analogy breaks downWill end up overriding most of the parents methods

InventoryItem

CategoryItem

-uniqueInstanceitemData

-Instance()ItemOperation()GetItemData()

described by

Page 8: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

8

Software Patterns are ...

Recurring solutions to common problems of design Practical/concrete solutions to real world problemsContext specific "Best-fits" for the given set of concerns/trade-offs"Old hat" to seasoned professionals and domain experts A literary form for documenting best practices A shared vocabulary for problem-solving discussions An effective means of (re)using, sharing, and building upon existing wisdom/experience/expertiseMassively hyped!

Page 9: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

9

History of Patterns

Writings of architect Christopher Alexander (coined this use of the term "pattern" ca. 1977-1979) Documentation of best practices and handbooks for engineering and architecture Literate programming (Don Knuth), ca. 1984 Kent Beck and Ward Cunningham, Textronix, OOPSLA'87 (used Alexander's "pattern" ideas for Smalltalk GUI design) Erich Gamma, Ph. D. thesis, 1988-1991 James Coplien, Advanced C++ Idioms book, 1989-1991 Gamma, Helm, Johnson, Vlissides ("Gang of Four")Object-Oriented Design Patterns book, 1991-1994 PLoP Conferences and books, 1994-present

Page 10: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

10

Kinds of Software Patterns

Design Patterns (software design; often object-oriented):

FundamentalCreationalBehavioralStructural

Analysis Patterns (recurring & reusable analysis models) Architectural Patterns (between analysis and design; recurring implementation structures)Domain-specific - Any domain you can think of!

Page 11: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

11

Defining A Pattern

No standard form yetPLoP conference is working on it

Common Formats“Alexandrian Form”

used Alexander's work

“GoF Form”“Canonical Form”

Page 12: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

12

Essential Elements of a Pattern

NameA meaningful "conceptual handle" for discussion

ContextTells how the problem occurs / when the solution works

ProblemStatement of the problem / intent of the solution

ForcesTrade-offs, goals+constraints, motivating factors/concerns

Tells why the problem is difficult

SolutionTells how to generate the solution

The solution structure, its participants & collaborations

Page 13: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

13

Essential Elements of a Pattern

Examples (optional)Resulting Context

Describes the end result, benefits and consequences Shows how the forces were balanced/traded-off

Tells how the solution works out Rationale (optional)

Underlying principles/heuristics justifying the solution Tells underpinnings of why the solution works out

Related PatternsPatterns which are similar, or which may precede/follow this one

Known Uses3 or more independent instances of "real world" success

Page 14: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

14

GoF Form

Pattern Name (Scope, Purpose)Name convey essence of pattern succinctly

IntentShort statement answering questions:

What does the design pattern do?

What is its rationale and intent?

What particular design issue or problem does it address?

Page 15: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

15

GoF Form (cont.)Also Known As

Other well-known names for the pattern, if any

MotivationScenario that illustrates

design problem

how class & object structures in pattern solve problem

Helps understanding the more abstract description that follows

Page 16: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

16

GoF Form (cont.)

ApplicabilityWhat situations can applied pattern?

Examples of poor designs that pattern addresses?

How to recognize situations? An applicable situation

Page 17: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

17

GoF Form (cont.)

StructureParticipants

Describe for each Class/object participating in pattern

Participant Name

Responsibility

CollaborationsHow the participants collaborate

Relations

Page 18: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

18

GoF Form (cont.)

ConsequencesHow pattern support its objectives?

Trade-offs & results of using pattern?

What aspects of system structure can you vary independently?

Page 19: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

19

GoF Form (cont.)

ImplementationAre there language-specific issues?

Pitfalls

Hints

Techniques

Page 20: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

20

GoF Form (cont.)

Sample Code & UsageCode fragments illustrating implementation

Known UsesExamples of pattern found in real systems.

Page 21: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

21

GoF Form (cont.)

Related PatternsWhat design patterns are closely related to this one?

What are the important differences?

With which other patterns should this one be used?

Page 22: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

22

GoF Form Example: Singleton

Name: SingletonIntent: ensure a class has only one instanceMotivation: It is important for some classes to have exactly one instance, like one file system, one window managerApplicability:

- when there must be exactly one instance of a class- when the sole instance should be extensible by

subclassing

Structure: shown earlier as a class diagram

Page 23: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

23

GoF Form Example: Singleton (cont.)

Participants- defines an Instance operation that lets clients access

unique instanceCollaborations- clients access a Singleton instance solely through

Singleton’s Instance operationConsequences-controlled access to sole instance-reduced name space-permits refinement of operations and representationImplementation: discussing implementation issuesSample Code: class/interface descriptions in a specific languageKnown Uses: InterViews user interface toolkit

Page 24: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

25

Why Patterns?Software Patterns help us because they:

Solve "real world" problems Capture domain expertise Document design decisions and rationale Reuse wisdom and experience of master practitioners Form shared vocabulary for problem-solving discussion Show more than just solution:

context (when and where) forces (trade-off alternatives, misfits, goals+constraints) resolution (how and why solution balances forces)

Page 25: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

26

Abuse of Patterns

Beware of unnecessary generalizationUtility/Generality tradeoff

Obscuring structurePerformance overheadEffort required to identify and adapt patterns (value/effort)Tricky platform dependencies

Page 26: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

27

Abuse (cont.)

Software Patterns are not ...Panacea or "silver bullet"

Little inspiration, mostly perspiration

Restricted to software design or Object-Oriented design Untested ideas/theories or new inventions Solutions that have worked only once Any old thing written-up in pattern format Abstract principles or heuristics Universally applicable for all contexts

Page 27: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

28

Ubiquitous Problems and Simple Design Patterns

Page 28: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

29

Problems of Redundancy

Problem: Many elements in a system will share similar structures and/or functionalityCommon solutions:

Subroutines and modulesInheritance

Define new structure and/or functionality then define a static relationship with “parents” to use theirs

Implementation (operations and attributes)Interface (sub-type)

CompositionCombine common “parts” then define new structure and/or functionality as necessary

Page 29: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

30

Object Interfaces and Types

Interface to an objectSet of all operation signatures

Note: this is not the same as a java “interface”

Type Named set of particular operation signaturesType that specializes another type is called subtype

Helps reduce redundancy by enabling Dynamic binding

Known types allow runtime mapping of requests to an objects operations

PolymorphismObjects of same type can be substituted at runtime

Page 30: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

31

Inheritance

Class (of an object):Defines interface and implementationAn object instantiated from a Class

A subclass has all the interface and implementation of particular other Classes

The other classes are “parents” of the subclassThe subclass is said to “inherit” from its parents

An abstract class is never instantiatedmainly used to define an interface

A leaf class is never subclassed A concrete class is anything else

Page 31: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

32

Interface vs. InheritanceClass (state+operations) vs. type (interface)Proper inheritance

derived classes should share same interfacesAdd or override, not hide parent operationsHeuristic: inherit for subtype only!

Interface defined by abstract classes allow clients to remain unaware of internal details (reduces implementation dependencies)

Principle 1: Program to an INTERFACE not implementation! Creational patterns ensure this principle

Singleton, Abstract Factory, Builder, Factory, etc.

Page 32: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

33

Fundamental Design Patterns

Delegation [Grand]Interface [Grand]Immutable [Grand]Relational Objects [???]

We will also introduce a Structural Pattern:Composite [GoF]

Page 33: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

34

Delegation [Grand]

A relationship between objects where one object forwards certain method calls to another object (delegate)

Powerful design/reuse technique

SecurityOption

delegates price info to

Page 34: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

35

Designing Bi-directional Relationships

Person Company

employedBy

Person Company

1

1..*

employedBy

employs

exists

+employee 1

+employer1..*

Issues: -Where are “jobs”? (e.g. where does “salary” live?) -How does the Company find an employee?-Would you create Employee and Employer subclasses?

Page 35: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

36

Relational Attributes and Selectors

Person CompanyemployeeSlot:1..1

1..*

myEmployee employees

1..*+employee

1..1

PersonjobSlot:

0..1Company

1

myJob

0..1

theCompany

1

+employer

salary

Person Company

employment

Employee #

salary

Relational objects

Solution: add Relational objects and delegate!

Page 36: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

37

Multi-Way Relationships

Reference Material

Library

Personreference librarian

How do you handle three simultaneously related components?- Reference Material housed in a Library managed by a reference librarian and all other permutations and combinations- Inheritance is no help here- This is a very common analysis problem, fortunately there is usually a nice solution!

Page 37: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

38

Relational Component

Reference material

Library

Person

Reference desk

reference librarian

Introduce a Relational Component (to be designed with appropriate objects later as needed) to manage the relationships.-Usually the Relational Component will have a reasonable counterpart in the domain - Introduce a specialized object if no counterpart in the domain exists

Page 38: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

39

Inheritance vs. Delegation

Inheritance is inappropriate for many situations, supports “is a kind of” relationship

creates strong, static coupling between class and subclasses

Delegation gives run time flexibility, although less structured, harder to understand

Page 39: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

40

Delegation

Use when you don’t have static rel’n between classes, e.g.. Role managementInstead of inheriting window from rectangle (window is not a rectangle), have the shape related methods delegated to rectangle (shape) objectUsed heavily in Java, for example Java’s event model:

EventSource’s usually do nothing with an event and pass it on to EventListener’s to process

Most all design patterns use delegationHeavy use in State, Strategy, Visitor, Proxy, Decorator

Page 40: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

41

Designing Roles with Delegation

Page 41: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

42

Component Roles

Person

Hancock VirtualMuseum

Person

Person

+board member

+curator

+patron

Page 42: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

43

Example Inheritance Solution

Hancock VirtualMuseum Person

Patron BoardMember Curator

Page 43: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

44

Example Inheritance Solution

What if a Patron becomes a Board Member?.etc.

Hancock VirtualMuseum Person

Patron BoardMember Curator

Page 44: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

45

Designing Object Roles

aPatronRoletheCuratorRole aBoardMemberRole

Person Person Person

Hancock VirtualMuseum

Page 45: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

46

Example Inheritance Hierarchy

PersonRole

PatronRole BoardMemberRole CuratorRole

Hancock VirtualMuseum Person

Page 46: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

47

Designing Multi-target Roles

aPatronRole.

aPatronRole

Implies re-classification of Patron Role

HancockVirtualMuseum

Person

Museum

Page 47: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

48

Multi-role Target

selected from

selector

PersonHancock Virtual

Museum aBoardMemberRole:

theDirectorRole:

Page 48: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

49

Designing Components

aPatronRole:

aPerson:

0..1

personRole

0..1

Person

Page 49: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

50

Inheritance vs. Composition

White-box reuse (subclassing): Uses visible implementations+ easy to use/modify

static, tends to breaks encapsulation, limited flexibility

Black-box reuse (composition): Uses hidden implementations+ dynamic, less dependencies

more objects, complex relationships and dependencies

Principle 2: Favor composition over inheritance

Page 50: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

51

Example Use of Compositions: Component

Based Subtyping

Page 51: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

52

Design Patterns:Expanding Classifications

PlatinumPCC

CreditCard

Corporate CC PersonalCC

StandardCCC PlatinumCCCGoldCCC StandardPCC GoldPCC

Page 52: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

53

Expanding Classifications Have Redundancy

Repetitive Layer

CreditCard

Corporate CC PersonalCC

StandardCCC PlatinumCCCGoldCCC StandardPCC GoldPCC PlatinumPCC

Page 53: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

54

Component Based Sub-typing

Card Type

Standard Gold Platinum

CreditCard

Corporate Personal

Page 54: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

55

CBS Class and Instance Diagrams

GoldcardType

AGoldPersonalCreditCard

aPersonalCreditCard

Card Type CreditCard

Page 55: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

56

Composite [GoF]

Designed to implement collection of classesUse to

build part-whole hierarchies orconstruct data representation of treeswhen you want your clients to ignore the difference between compositions of objects and individual objects

Page 56: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

57

Composite Pattern Example

Character

getCharLength() : int

Image

getCharLength() : int

DocumentElement

getFont() : FontsetFont(font : Font)getCharLength(item : Graphic) : intgetParent(which : Integer) : CompositeDocumentElement

CompositeDocumentElement

draw()add(item : Graphic)remove(item : Graphic)getChild(which : Integer)

Document Page Column Frame LineOfText

*

1

Page 57: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

58

Composite Pattern General Form

ConcreteComponent1

operation()

ConcreteComponent2

operation()

AbstractComposite

operation()add(x : AbstractComponent)remove(x : AbstractComponent)getChild(x : int)

ConcreteComposite1

operation()add(x : AbstractComponent)remove(x : AbstractComponent)getChild(x : int)

ConcreteComposite2

operation()add(x : AbstractComponent)remove(x : AbstractComponent)getChild(x : int)

AbstractComponent

operation()*

1

Page 58: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

59

Composite Pattern Participants

AbstractComponent: abstract superclassConcreteComponent1,2: leaves of treeAbstractComposite: abstract superclass of all composite objects that participate in the Composite patternConcreteComposite1,2 : composite objects that use other instances of AbstractComponent

Page 59: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

60

Reasons/ConsequencesDefines class hierarchiesSimple Clients

Doesn’t know/care whether dealing with leaf or composite classUniform treatment of composite & individual object

Easier to add new componentsNew composites or leaves work automatically

Can make design over generalSometimes want a composite to have only certain components

Need run-time checks

Sharing components to reduce space when there is more than one parent is difficultIssue: which classes should declare operations for component management

Page 60: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

61

Known Uses/ Related Patterns

Almost all OO systemsView class of MVCComponent/Container class of java.awt

* Decorator,Flyweight, Iterator, Visitor

Page 61: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

62

Creational Patterns

Factory [GoF]Abstract Factory[GoF]Builder [GoF]Prototype [GoF]Singleton [GoF]Object Pool [Grand]

Page 62: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

63

Factory [GoF]

Define interface for creating object, let subclasses decide which class to instantiate. Reusable class delegates this choice, and refers to new object by interface

Page 63: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

64

Factory Pattern Example

Socket

DESEncryption

EncryptionFactory

createEncryption(key) : Encryption

*

1

RSAEncryption

*

1

EncryptionFactoryIF

createEncryption(key)

<<Interface>>

Encryption

encryptedOutputStream()encryptedInputStream()

EncryptedSocket

EncryptedSocket(key, EncryptionFactoryIF)getInputStream()getOutputStream()

*

1

1

*

1 1

* *

creates creates

+creator

+requestor 1

*

*

1+byte source

+encryptor/decryptor

requests creation

encrypts/decrypts bytes

Page 64: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

65

Factory Pattern General Form

ConcreteProduct

operation1()operation2()

FactoryIF

createProduct(discriminator : String) : Product

<<Interface>>

CreationRequestor

newProduct()

1

1

+creator1

+requestor1

Requests creation

Product

operation1()operation2() * 1* 1Uses

Factory

createProduct(discriminator : String) : Product

*

1

*

1

Creates

Page 65: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

66

Factory Pattern Participants

Product : abstract superclass of objects produced by the patternConcrete Product : subclasses of productCreationRequestor : application independent class creating app specific classesFactoryIF: application independent interface, creation method takes args to deduce the class to instantiateFactory: application specific class that has a method to create Concrete Products

Page 66: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

67

Reasons/Consequences

Set of subclasses to be instantiated may be dynamic as new classes are availableClass must create objects without knowing what subclasses are there

* Creation requestor class independent of class of created concrete product objects

* Subclasses of product class may change dynamically

Page 67: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

68

Known Uses / Related Patterns

JAVA API: URLConnection, getContent method returns different image files, docs..EJB Creation ModelToolkits, frameworks: Unidraw

* Abstract Factory, Template, Prototype

Page 68: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

69

Abstract Factory [GoF]

One level of abstraction higher than FactoryCreates families of related classesWhen your system needs to support multiple UI for Windows, Mac, Motif

Page 69: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

70

Abstract Factory ExampleArchitecture Toolkit

getFactory()createCPU()createMMU()

CPU MMU

Client

Uses

*

1

*

1

Uses

**

1

Uses

EmberCPU EmberMMU

EmberToolkit

createCPU()createMMU()

*

1

*

1

Creates

*

1

*

1

Creates

EnginolaCPU EnginolaMMU

EnginolaToolkit

createCPU()createMMU()

*

1

*

1

Creates

*

1

*

1

Creates

Page 70: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

71

Abstract Factory General Form

AbstractFactory

getFactory()createA()createB()

WidgetA WidgetB

Client

Uses

1

*

1

Uses

*

1

*

1

Uses

Product1WidgetA Product1WidgetB

ConcreteFactory1

createA()createB()

*

1

*

1

Creates

*

1

*

1

Creates

Product2WidgetA Product2WidgetB

ConcreteFactory2

createA()createB()

*

1

*

1

Creates

*

1

*

1

Creates

Page 71: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

72

Abstract Factory Participants

Client: only know about abstract widgets AbstractFactory: define abstract methods for concrete widget instancesConcreteFactory1,2: implement methods to create instances of concrete widgetsWidget A,B : abstract widgetsProduct1WidgetA,..:concrete widgets that correspond to a feature of a product

Page 72: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

73

Reasons/ Consequences

A system independent of how its products are created/composed/representedA system configurable with one of multiple families of productsYou want to reveal only interfaces of a class library of products

* It isolates concrete classes* Makes exchanging product families easy* Promotes consistency among products* Supporting new kinds might be difficult

Page 73: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

74

Known Uses/ Related Patterns

JAVA API, awt toolkitET++, OO application framework in C++ for portability

* Factory, Prototype, Singleton

Page 74: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

75

Structural Patterns

Adapter [GoF]Bridge [GoF]Composite [GoF] (already covered)Decorator [GoF]Façade [GoF]Flyweight [GoF]Proxy [GoF]

Page 75: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

76

Behavioral Patterns

Chain of Responsibility [GoF]Command [GoF]Interpreter [GoF]Iterator [GoF]Mediator [GoF]Memento [GoF]Observer [GoF]State [GoF]Strategy [GoF]Template [GoF]Visitor [GoF]

Page 76: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

77

Observer [GoF]

Define dependency between objects so that when one object changes state, all its dependents are notified

Page 77: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

78

Observer Pattern Example

SecurityObserver

ALARM:int=1 {frozen}LOW_POWER:int=2 {frozen}DIAGNOSTIC:int=3 {frozen}

notify(device : int, event : int)

<<Interface>>

SecurityClientSecurityAdapterSecurityMonitor

1 1Notifies

1 1

SecurityNotifier

addObserver( : SecurityObserver)removeObserver( : SecurityObserver) 0..*

Notifies

Page 78: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

79

Observer Pattern General Form

Observer

ObservableIF

addObserver( : ObserverIF)removeObserver( : ObserverIF)

<<Interface>>

Observable

ObserverIF

notify()

<<Interface>>

10..* 10..* registers to receive notifications

Multicaster

addObserver( : ObserverIF)removeObserver( : ObserverIF)

1

1Notifies, registers observers

0..*0..*

Notifies

1

1

Page 79: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

80

Observer Pattern Participants

ObserverIF: defines notify or updateObserver: receive state change notificationsObservableIF: defines two methods that allow Observer objects to un/register to receive notificationsObservable: responsible for managing the registration of ObserverIF objects, delivering the notifications. It delegates those responsibilites to Multicaster object,Multicaster: delivers notifications to ObserverIF objects on behalf of an Observable Object

Page 80: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

81

Reasons/ Consequences

When change in one object requires changing othersWhen object should be able to notify other objects without knowing who they are

* Support for broadcast communication* Delivering notifications can take long time if

there are a lot of objects to deliver notifications to

* Watch out for cyclic dependencies, dangling references to deleted subjects

Page 81: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

82

Known Uses/ Related Patterns

Java’s delegation even model as a specialized form, eventlisteners

* Adapter, Delegation, Mediator

Page 82: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

83

Strategy [GoF]

Encapsulate a family of related algorithms, make them interchangeable, provide a way to choose the most appropriate one

Page 83: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

84

Strategy Pattern Example

USHoliday CanadaHoliday Composite Holiday

uses one or more holiday, aggregation

Calendar Display Holiday

getHolidays( : Date) : String[]0..111 0..1

Uses

Page 84: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

85

Strategy Pattern General Form

ConcreteStrategy1 ConcreteStrategy2

Client AbstractStrategy

operation()0..111 0..1

Uses

Page 85: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

86

Strategy Pattern Participants

Client: delegates the operation to an abstract class or interfaceAbstractStrategy: a way to access the operation encapsulated by its subclassesConcreteStrategy1,2: alternative implementation of the operation

Page 86: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

87

Reasons / Consequences

You need different variants of algorithmMany related classes differ only in their behavior

*Eliminates conditional statements* Provide a choice of implementations* Communication overhead between Strategy and Context

* Increased number of objects

Page 87: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

88

Known Uses / Related Patterns

Borland’s ObjectWindowsET++ and Interviews use this pattern for line breaking algorithms

* Flyweight

Page 88: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

89

Back to our EJB Pet Store

Models use Strategy

Ex: ModelManager.java

a single point of access to all Model objects. (OrderModel.java, CartModel.java, etc.)

Views use Composite, Facade

Ex: template.jsp (master template)

RequestProcessor.java

Customer.java

Controllers use Observer, Proxy

Ex: MainServlet.java

ShoppingClientControllerEJB.java

Page 89: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

90

Identification & Application of Design Patterns

Page 90: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

91

Finding Appropriate ObjectsDecomposing system into objects

Many factorsGranularity, dependency, performance, evolution, ...

Many techniques

Challenge: mapping different paradigms efficientlyDesign Patterns help identify less-obvious abstractions & objects

e.g. ones that don’t occur in nature (domain); but help achieve flexible design

Page 91: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

92

System FactoringEdward Colbert:

What goes hear?

Edward Colbert:

What goes hear?

Page 92: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

93

GoF Pattern Relationships

Page 93: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

94

Design for ChangeCreating an object by specifying a class explicitly (Abstract Factory, Factory, Prototype)Dependence on specific operations (Command)HW/SW platform ,Object representation dependence (Abstract Factory, Bridge, Memento, Proxy)Algorithmic dependencies (Builder, Iterator, Strategy, Template, Visitor)Tight coupling (Abstract Factory, Bridge, Command, Façade, Observer)Extending functionality by subclassing (Bridge, Composite, Decorator, Observer)Inability to alter classes conveniently (Adapter, Decorator, Visitor)

Page 94: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

95

Example: MVCAEdward Colbert:

How’s different from p25?

Edward Colbert:

How’s different from p25?

Page 95: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

96

Model-View

aPatronInterface:

aUser:

0..1

theUser

0..1

model

view

Page 96: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

97

Model-Controller-View

model

viewaPatronInterface:

aPatronController:

1..1

aUser: 0..1

myPatronInterface

theUser

1..1

0..1

controller

Page 97: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

98

Model-Controller-Association-View

association

view

controller

aUser:

aPatronController:

0..*0..*

theUsers

aPatronAssociation:

aPatronInterface:

anAuthorizationAssociation:

theAuthorizationInterface:

myAssociations muAssociations

model

Page 98: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

99

A Good Pattern“Cope” says

Solves a problemnot just abstract principles or strategies

Is a proven concepthas a track recordnot just theories or speculation

Isn’t obviousgenerate a solution indirectlynot from first principles

Describes a relationshipnot just classes or modulesbut complete system structures & mechanisms

Has a significant human componentappeal to aesthetics & utility“elegant”

Small interface, large accessible, cohesive, coherent information

Page 99: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

100

Domain Specific Design Patterns

Page 100: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

101

Compiling a Repository of Patterns

TO DO-Pattern Name and Classification (short, meaningful name)-Problem (description of problem context, goals, constraints that occur, guidance in recognizing that pattern)-Solution (participants, their structures and collaborations, sample code optional)-Consequences (results, tradeoffs, Variations and language-dependent alternatives -Known Uses (real system examples)-Contribution (a popular repository WikiWikiWeb http://www.c2.com/cgi/wiki)NOT TO DO

Don’t make up patterns (use successfully at least 3 times before sharing)

Page 101: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

102

Pattern Resources: Internet

A Pattern Language: Towns, Buildings, Construction (APL), Christopher Alexander; Oxford University Press, 1977 The Timeless Way of Building (TTWoB), Christopher Alexander; Oxford University Press, 1979Design Patterns: Elements of Reusable Object-Oriented Software (GoF), Gamma, Helm, Johnson, Vlissides; Addison-Wesley, 1994Pattern-Oriented Software Architecture: A System of Patterns (POSA), Buschmann, Meunier, Rohnert, Sommerlad, Stal; Wiley and Sons, 1996 Pattern Languages of Program Design (PLoPD1), Coplien and Schmidt (editors); Addison-Wesley, 1995 Analysis Patterns: Reusable Object Models, Martin Fowler; Addison-Wesley, 1996 Pattern Languages of Program Design 2 (PLoPD2), Vlissides, Coplien, and Kerth (editors); Addison-Wesley, 1996 Pattern Languages of Program Design 3 (PLoPD2), Martin, Riehle, and Buschmann (editors); Addison-Wesley, 1997 Object Models: Strategies, Patterns, & Applications, Peter Coad with David North & Mark Mayfield; Prentice Hall, 1995

Page 102: 1 Introduction to Design Patterns. 2 Outline Introduction and Background Common and Simple Design Patterns Identification and Application of Design Patterns

103

Pattern Resources: Internet

Patterns Home Page, http://www.hillside.net/patterns/

Patterns Discussion FAQ, http://g.oswego.edu/dl/pd-FAQ/pd-FAQ.html

Ward Cunningham's WikiWikiWeb, http://c2.com/cgi/wiki?WelcomeVisitors

Portland Pattern Repository, http://www.c2.com/pp/

AGCS Patterns Page, http://www.agcs.com/patterns/

Jim Coplien's OrganizationPatterns Front Page (a WikiWikiWeb work-alike), http://www.www.bell-labs.com/cgi-user/OrgPatterns/OrgPatterns

Patterns Mailing Lists, http://www.hillside.net/patterns/Lists.html

Cetus Links: Patterns, http://www.objenv.com/cetus/oo_patterns.html

Brad's Pattern Links, http://www.enteract.com/~bradapp/links/sw-pats.html

Brad's Patterns Intro, http://www.enteract.com/~bradapp/docs/patterns-intro.html

Luke Hohmann's Patterns Intro, http://members.aol.com/lhohmann/papers.htm

Doug Lea's OOD Patterns Intro, http://gee.cs.oswego.edu/dl/ca/ca/ca.html