Technieken van de Software Architectuur, VUB ‘98-’99, Part 41 Part 4: Design Patterns.

Post on 01-Apr-2015

218 views 2 download

Tags:

Transcript of Technieken van de Software Architectuur, VUB ‘98-’99, Part 41 Part 4: Design Patterns.

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 1

Part 4: Design Patterns

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 2

Background

Designing reusable software is difficult» Finding good objects and abstractions» Flexibility, Modularity, Elegance» Takes time to emerge, trial and error

Successful designs exist How to describe recurring structures

» Deja-Vu feeling, don’t reinvent the wheel, don’t reinvent the flat tire.

Design Patterns: Elements of Reusable Object Oriented Software

» E. Gamma R. Helm R. Johnson J. Vlissides

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 3

Design Patterns

Design patterns capture successful solutions to recurring problems that arise during software construction

Design patterns help to improve key software quality factors

Design patterns support reuse of software architectures

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 4

A Design Pattern

Describes a recurring design structure» Used twice rule» Names, abstracts from concrete designs» Identifies classes, collaborations,

responsibilities» Applicability, trade-offs, consequences,

language issues

Is discovered, not invented

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 5

Practical Experience

Design Patterns are based on practical solutions found in main-stream applications implemented in Smalltalk and C++» Windowing Systems» CAD» Banking» Persistent Objects» Distributed Systems» ...

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 6

Describing Design Patterns

Pattern name and classification

Intent Also Known As Motivation Applicability Structure

Participants Collaborations Consequences Implementation Sample Code Known Uses Related Patterns

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 7

Catalogue of Design Patterns

Purpose» Creational» Structural» Behavioural

Scope» Class» Object

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 8

Structural Patterns

Adaptor Bridge Composite Decorator Facade Flyweight Proxy

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 9

Behavioural Patterns

Chain of Responsibility

Command Interpreter Iterator Mediator Memento

Observer State Strategy Template Method Visitor

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 10

Design Coverage

Large Portion of design covered by patterns» Most classes play role in some patterns» Improved understanding

Seductively simple to implement patterns You still have to write functionality

» Common mistake is to think design patterns solve your problems

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 11

Abstract Factory

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 12

Abstract Factory

Object Creational Intent: Provide an interface for creating

families of objects without specifying the concrete classes

Motivation: Creation of line segments, points, ... in a drawing framework

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 13

Abstract Factory: Motivation

ComponentFactory

newLine() {abstract}newPoint() {abstract}

GrayComponentFactory

newLine()newPoint()

ColorComponentFactory

newLine()newPoint()

Client

Line

ColorLine GrayLine

Point

ColorPoint GrayPoint

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 14

Abstract Factory: Applicability

Use the Abstract Factory Pattern when:» A system has to be independent of how its

objects are created, composed and represented

» Configuration with families of products is necessary

» A family of products is designed to work together

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 15

Abstract Factory: Participants

AbstractFactory (e.g. ComponentFactory)

ConcreteFactory (e.g. ColorComponentFactory)

AbstractProduct (e.g. Point) ConcreteProduct (e.g. ColorPoint) Client

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 16

Abstract Factory: Consequences

It isolates clients from concrete classes Makes exchanging of product families

easier It promotes consistency amongst

products Supporting new kinds of products is

difficult

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 17

Abstract Factory: Implementation

Factories are best implemented as Singletons

Creating the products» (1) Use a Factory Method for each product» (2) Initialize the concrete factory with a

prototypical instance that can be copied

Defining extensible factories» In AbstractFactory provide a parameter to

identify the product to be created

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 18

Bridge

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 19

Example: Variations in storage

InformixProgram

... findPrograms ...

Program

duration()productCode()broadcastitle (title: Title)static findPrograms (s:searchObject) : ProgramList...

IngresProgram

... findPrograms

OracleProgram

... findPrograms

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 20

The Original Persistency Layer

Allow non DB experts to work on the application Migration to other DB's Be ready for OO databases

Domain Model

Persistency Layer

Store

Retrieve

HematomasHematomas

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 21

bcPIDProgramID contractPID

Example

Program

contractPeriodbroadcastPeriod

Period

from: 01/01/96, 00h00 to: 01/02/96, 00h00

from: 07/01/96, 20h00 to: 07/01/96, 22h00

Period

ProgramTable:

PeriodTable: PeriodID fromDate fromHour toDate toHour

foreign key

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 22

Solution: Bridge Pattern

Intent: Decouple an abstraction from its implementation so that the two can vary independently

Motivation: Window Implementations

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 23

Bridge: Motivation

Window

DrawText()DrawRect

WindowImp

DrawText()DrawRect

TransientWindow

DrawCloseBox

IconWindow

DrawBorder()

Window95Imp

DrawText()DrawRect

XWindowImp

DrawText()DrawRect

Imp

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 24

Bridge: Applicability

Use the Bridge Pattern to» Avoid a permanent binding between an

abstraction and its implementation» Both the abstractions and their implementations

should be extensible by subclassing» To avoid proliferation of classes

Separation of Concerns

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 25

Bridge: Structure

Abstraction

Operation()

Implementor

OperationImp()imp

RefinedAbstraction

ConcreteImpB

OperationImp()

ConcreteImpA

OperationImp()

Client

Bridge Participants

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 26

Bridge: Consequences

Decoupling interface and implementation Improved extensibility Hiding implementation details from clients

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 27

Implementation ObjectKnows how to map itself to a relational database

Implementation ObjectKnows how to map itself to a relational database

The Bridge Architecture

A

B

C+D

Conceptual ObjectContains business rules

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 28

DomainObjectstore()initialize()storage ()

The Bridge Architecture

StorageObject

...Programtitle(t:Title)

BasicStorage AdaptorStorage

FlattenedStorage

HierarchyStorage

Mapping Strategies

storagedomain

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 29

Bridge: Basic Mappings

DomainObjectstore()initialize()...

StorageObject

Firmname(s:String)...

BasicStorage

FirmStoragename:Stringname (s:String)...

name [name]

nameaddr...

PSIFirmTable

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 30

Bridge: Basic Mappings

A commercially available framework is used for the basic mappings (Object Lens)

The abstract classes contain behavior for querying, retrieval, etc. of data

The basic mappings are database independent

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 31

Bridge: Mappings of Classes

A

B

C C

B

A+B+C

A

FlattenedStorage

HierarchyStorage

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 32

FlattenedStorage

Bridge: FlattenedStorage

DomainObject

Contract

SalesContract PurchaseContract

StorageObject

BasicStorage

ContractStorage

date:Stringdate (s:String)

...

nameaddrclassID

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 33

BProgramStorage

Bridge: HierarchyStorage

DomainObject

Program

Episode

StorageObject

BasicStorage

BEpisodeStorage

HierarchyStorage

ProgramStorage

EpisodeStorage

programPart

episodePart

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 34

Bridge: Adaptor Mapping

Program

broadcastPeriodcontractPeriod

Period

from: 01/01/96, 00h00 to: 01/02/96, 00h00

from: 07/01/96, 20h00 to: 07/01/96, 22h00

Period

ProgramTable

bcFromDatebcFromTimebcToDatebcToTimecntrFromDatecntrFromTime...

bcFromDatebcFromTimebcToDatebcToTimecntrFromDatecntrFromTimecntrToDatecntrToTime

ProgramStorage

Conceptual Objects Implementation Objects

BCPeriodStorage

Database

toDate[toDate]

toDate[bcToDate]

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 35

Bridge: Adaptor Mapping

DomainObjectstore()initialize()...

StorageObject

Periodfrom():Timeto(): Time

BasicStorage

ProgramStoragebcFrom:DatebcTo:Date

AdaptorStorage

BCPeriodStoragefrom():Timeto():Time

Adaptor design pattern

to [bcTo]

adaptee

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 36

Adaptors

Period

to():Timefrom(): TimeincludesTime(t:Time):Booleanmerge(p:Period):Period

PeriodAdaptor

PeriodImpl

to:Timefrom: Timeto():Timefrom(): Time

Period

to():Timefrom(): TimeincludesTime(t:Time):Booleanmerge(p:Period):Period

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 37

Observer

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 38

Observer

Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

15,20,40

Motivation: Maintain consistency between objects without a tight coupling that reduces reusability.

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 39

Observer : Applicability

Use Observer when» an abstraction has two aspects, one dependent on the

other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.

» a change to one object requires changing others, and you don’t know how many objects need to be changed

» an object should be able to notify other objects without making assumptions about who these objects are.

Separation of Concerns

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 40

Observer : Structure

Subject

attach(Observer)dettach(Observer)Notify()

Observer

update()

ConcreteObserverobserverState

update()

state

ConcreteSubjectsubjectState

getState()setState()

forall o in observers o update

return subjectStateobserverState= subject subjectState

Observer Participants

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 41

Observer : Consequences

abstract coupling between subject and observer

support for broadcast communication unexpected updates

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 42

State

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 43

State

Object Behavioral Intent: Allow an object to alter its

behavior when its internal state changes. The object will appear to change its class

Motivation: Network connection

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 44

State: Motivation

TCPConnection

open ()close()

TCPState

clone()

TCPListen

open()close()

TCPClosed

open()close()

state

TCPEstablished

open()close()state close()

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 45

State : Applicability

Use State» when an object’s behavior depends on its

state and it must chaneg its behavior at runtime

» when operations have large conditional statements that depend on the state of the objects

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 46

State : Participants

Context (e.g. TCPConnection) State (e.g. TCPState) ConcreteState (subclasses of State)

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 47

State : Structure

Context

request()

State

handle()

TCPListen

handle()

TCPClosed

handle()

state

TCPEstablished

handle()state handle()

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 48

State : Consequences

separates state-specific behavior from general behavior

Makes state-transitions explicit State objects can be shared

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 49

Composite

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 50

BUT?

How to combine ?- multiple inheritance- mixin classes

+

Node

LoggingNode WorkstationPrintserver

Node

Separate discussion(design patterns)

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 51

...

...

Program

duration()productCode()broadcastitle (title: Title)static findPrograms (s:searchObject) : ProgramList...

Example: Variations in the domain

Series

...

Episode

...

... ...

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 52

Example: Variations in the domain

ComposedProgram

duration ()

Program

duration()broadcastitle (title: Title)static findPrograms (s:searchObject) : ProgramList...

ProgramSlice

duration ()

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 53

Combining variations

Duplication of behavior » Not a satisfying solution» Proliferation of versions

Concentrate behaviour» Not a satisfying solution» Overfeaturing

ProgramSlice

Program

Episode

EpisodeSlice

Program

isSlice...

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 54

Composite Programs

ComposedProgram

duration ()

Program

duration()...

SeriesEpisode

duration [duration]

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 55

A Solution

Program

duration()...

SeriesEpisode

Structure

duration()...

Composedduration()

Atomicduration()

Slicedduration()

concretisationparts

duration [duration]

Separation of Concerns

State design pattern

Composite design pattern

structure

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 56

Decorator

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 57

Decorator: Participants

Component (e.g. VisualComponent) ConcreteComponent (e.g. TextView) Decorator (e.g. Decorator) ConcreteDecorator (e.g.

BorderDecorator)

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 58

Decorator: Structure

Component

Operation()

ConcreteComponent

Operation()

Decorator

Operation()

component

ConcreteDecoratorAadded stateOperation()added behaviour

ConcreteDecoratorBadded stateOperation()added behaviour

component operation

super operationadded behaviour

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 59

Decorator: Consequences

More flexible than static inheritance. Avoids classes with a lot of features

» Refactoring method !» Lots of little objects» Avoids duplication of features

Object identity can be a problem

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 60

Decorator: Participants

Component (e.g. VisualComponent) ConcreteComponent (e.g. TextView) Decorator (e.g. Decorator) ConcreteDecorator (e.g.

BorderDecorator)

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 61

Decorator: Structure

Component

Operation()

ConcreteComponent

Operation()

Decorator

Operation()

component

ConcreteDecoratorAadded stateOperation()added behaviour

ConcreteDecoratorBadded stateOperation()added behaviour

component operation

super operationadded behaviour

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 62

Decorator: Consequences

More flexible than static inheritance. Avoids classes with a lot of features

» Refactoring method !» Lots of little objects» Avoids duplication of features

Object identity can be a problem

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 63

Design Patterns in Practice

Architectural Layers

Integration

Redundancy

Data Warehousing

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 64

Firstname

Lastname

Age

Person Editor

Person

Person

Reusable Objects/Components

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 65

Firstname

Lastname

Age

Person Editor

Person

Person

Application Layer

Application Layer

Domain Layer

Domain Layer

Persistency Layer

Persistency Layer

Separation of Concerns

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 66

Application LayerApplication Layer

Domain LayerDomain Layer

Persistency LayerPersistency Layer

Drawing Editor Firstname

Lastname

Age

Person Editor

License

Brand

Age

Car Editor

Person

CarDrawing

Layered Architecture

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 67

Bridge: Integration

PSI

PSI DB

OtherApplication

External DB

Bridge

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 68

Controlling Redundancy

FirmID

Firm Name

Title

Program Editor StorageObject

BasicStorage

FirmStoragename:Stringname (s:String)id: Sringid (s:String)

ProgramStoragefirmName:StringfirmName (s:String)firmId: SringfirmId (s:String)...

Updates programStorage if name or

id changes

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 69

Data Warehousing: CASE

NumberAmount

Owner

Account Editor

Application

RDBMSMainframe

Application for account managementCICS Transactions Mirrored DB...

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 70

AccountStorage

amount(): Integerowner(): Owner...

Data Warehousing: CASE

Account

amount(): Integerowner(): Owner...

storage

Brid

ge

NumberAmount

Owner

Account Editor

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 71

AccountStorage

amount(): Integerowner(): Owner...

Data Warehousing: CASE

Account

amount(): Integerowner(): Owner...

storage

Brid

ge

NumberAmount

Owner

Account Editor

Transaction

CICS

CICS1234

CICS1235

Adaptor

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 72

AccountStorage

amount(): Integerowner(): Owner...

Data Warehousing: CASE

Account

amount(): Integerowner(): Owner...

storage

Brid

ge

NumberAmount

Owner

Account Editor

Transaction

CICS

CICS1234

CICS1235

Adaptor

CICSAccountAmount

set(amount: Integer)get(): Integer

Facade

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 73

Data Warehousing

Account

amount(): Integerowner(): Owner...

storageAccountStorage

amount(): Integerowner(): Owner...

Transaction

CICS

CICS1234

CICS1235

CICSAccountAmount

set(amount: Integer)get(): Integer

Facade

Adaptor

AccountBasicStorage

Brid

ge

NumberAmount

Owner

Account Editor

Technieken van de Software Architectuur, VUB ‘98-’99, Part 4 74

Bridge: Summary

Provides a clean separation between domain and storage

Allows easy integration with other systems

Various mappings had to be included» NOT part of the Bridge Design Pattern