1 Design Patterns Tom Mens FWO Postdoctoral Fellow Programming Technology Lab Vrije Universiteit...

125
1 Design Patterns Tom Mens FWO Postdoctoral Fellow Programming Technology Lab Vrije Universiteit Brussel

Transcript of 1 Design Patterns Tom Mens FWO Postdoctoral Fellow Programming Technology Lab Vrije Universiteit...

1

Design Patterns

Tom MensFWO Postdoctoral Fellow

Programming Technology Lab

Vrije Universiteit Brussel

2

Presentation Overview

A. Introduction to Design Patterns Background Context and definition A first example Design patterns vs OO frameworks

B. Discussion of Design PatternsC. AntiPatternsD. Conclusion

3

A. Introduction toDesign Patterns

4

Main Reference

Design PatternsElements of ReusableObject-Oriented Software

E. Gamma, R. Helm,R. Johnson, J. Vlissides(the “Gang of Four”)

Addison-Wesley, 1995ISBN: 0-201-63361-2

A

5

Background …

Designing Reusable Software is hard Find classes with right granularity Define interfaces and inheritance hierarchies Establish key relations between classes Inheritance or Composition ? Attribute or Association ? Association or Aggregation ? Flexibility, Modularity, Elegance

A

6

Background …

Reusable solutions should solve a specific problem, but at the same time be general enough to address future problems and requirements

Takes time to emerge, trial and error Requires experience

A

7

Background

Aha-erlebnis / déjà-vu feeling

Don’t reinvent the wheel

Don’t reinvent the flat tire

Everything boils down to

A

8

What is a Pattern?

“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 Patterns in

OOSE ?

A

9

Types of Patterns

Design Patterns Gang of Four

AntiPatterns Brown&al.1998

Analysis Patterns Fowler1997

Organisational Patterns Coplien

Software Configuration Management Patterns Brown&al.1999

Pattern Languages of Program Design Coplien&al.1995, Vlissides&al.1996, Robert&al.1997

A

10

Design Patterns …

“Design patterns are descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context”

Gang of Four

A

11

Design Patterns …

describe a recurring design structure “Used twice”-rule Abstracts away from concrete designs Identifies participating classes and objects,

their roles and collaborations,distribution of responsibilities

Applicability, trade-offs, consequences, language issues

A

12

Design Patterns …

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

are discovered, not invented

A

13

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 all your problems

A

14

Why use design patterns?

Reuse proven design (solutions) from prior experiences Gain design confidence Structure design

Common vocabulary amongst designers Within and across teams

DocumentationImprove key software quality factors reusability, extendibility, …

A

15

A First Example:The Problem

Entangled hierarchies: behaviour and visualisation of UI objects are combined in same inheritance structure

A

Widget

Window Button Scrollbar

MSWindow MacWindow MSButton MacButton MSScrollbar MacScrollbar

16

A First Example:The Solution

Use Abstract Factory: separate behaviour of UI objects from their visualisation

A

MSLook

newWindownewButton

MacLook

newWindownewButton

Look

newWindownewButton

Widget

Window Button

MSWindow

MacWindowMacButton

MSButton

17

Abstract Factory: Applicability

This solution can be applied in general when a system should be independent of how its products are

created, composed, and represented a system should be configured with families of

products you want to provide a class library of products, and you

want to reveal just their interfaces, not their implementations

a family of related product objects is designed to be used together, and you need to enforce this constraint

A

18

Abstract Factory: StructureA

Normally a single instance of ConcreteFactory is created at run-time

AbstractFactory defers creation of product objects to its ConcreteFactory subclass

19

Abstract Factory: Participants

AbstractFactory (Look) declares an interface for operations that create abstract product objects

ConcreteFactory (MSLook, MacLook) implements the operations to create concrete product objects

AbstractProduct (Window, Button) defines a product object to be created by the corresponding concrete

factory implements the AbstractProduct interface

ConcreteProduct (MacWindow, MSButton, …)Client uses only interfaces declared by AbstractFactory and AbstractProduct

classes

A

20

Design Patterns vs Frameworks

“A framework is a set of cooperating classes that make up a reusable design for a specific class of software”

Peter Deutsch

A

21

Design Patterns vs Frameworks

Both frameworks and design patterns are ways of describing and documenting solutions to common problems

Design patterns are not frameworks

Patterns are more abstract many patterns are involved in the solution of

one problem

A

22

Design Patterns vs Frameworks

Frameworks codify designs for solving a family of

problems within a specific domain are instantiated by inheritance and composition

of classes can contain several instances of multiple design

patterns are more “shrink-wrapped”, ready for

immediate use

A

23

Design Patterns vs Frameworks

Design patterns are• more abstract• smaller architectural elements• less specialized

than frameworks

Summary:

A

24

25

Presentation Overview

A. Introduction to Design PatternsB. Discussion of Design Patterns

Design pattern catalogue Example 1: Factory Method Example 2: Builder Example 3: Composite Example 4: Decorator Example 5: Strategy Example 6: State Example 7: Visitor

C. AntiPatternsD. Conclusion

26

B. Discussion ofDesign Patterns

27

Design Pattern Catalogue …

Purpose reflects what a pattern does

Scope specifies whether the pattern applies

primarily to classes or to objects

Classification of Design Patterns based on two criteria:

B

28

Design Pattern Catalogue …

Purpose Creational

are concerned with the process of object creation Structural

are concerned with how to compose classes and objects in larger structures

Behavioural are concerned with algorithms and the separation

of responsibilities between objects or classes

B

29

Design Pattern Catalogue …

Scope Class Patterns

deal with relationships between classes (and their subclasses)

relationships are static since they are fixed at compile time

Object Patterns deal with relationships between objects relationships are more dynamic since they can be

changed at run-time

B

30

Design Pattern Catalogue …

Purpose

Creational Structural Behavioral

Scope Class Factory Method Adapter (class) Interpreter

Template Method

Object Abstract Factory

Builder

Prototype

Singleton

Adapter (Object)

Bridge

Composite

Decorator

Façade

Flyweight

Proxy

Chain of Responsibility

Command

Iterator

Mediator

Memento

Observer

State

Strategy

Visitor

B

31

Design Pattern Catalogue …

Abstract the instantiation/object creation process Encapsulates knowledge about which concrete classes to use Hides how class instances are created and put together

Gives a lot of flexibility in what gets created, who creates it, how it gets created, and when it gets created

A creational class pattern uses inheritance to vary the class that is instantiated

A creational object pattern delegates instantiation to another object

Creational Patterns

B

32

Design Pattern Catalogue

Are concerned with how classes and objects are composed to form larger structures When/how should you use inheritance? When/how should you use aggegration, association, composition?

A structural class pattern uses inheritance to compose interfaces or implementation compositions are fixed at compile time

A structural object pattern describes ways to compose objects to realise new functionality the added flexibility comes from the ability to change the

composition at run-time

Structural Patterns

B

33

Design Pattern Catalogue

Are concerned with algorithms and the assignment of responsibilities between objectsA behavioral class pattern uses inheritance to distribute behavior between classesA behavioral object pattern uses object composition rather than inheritance describes how a group of objects cooperate to perform a tasks no

single object can carry out by itself is concerned with encapsulating behavior in an object and

delegating requests to it

Behavioral Patterns

B

34

Describing Design Patterns

Pattern name and classification

Intent

Also known as

Motivation

Applicability

Structure

Participants

Collaboration

Consequences

Implementation

Sample Code

Known Uses

Related Patterns

B

35

How to selecta design pattern

Consider how the design patterns solve a problem

Study the intent section of the design patterns

Study patterns of similar purpose

Consider what should be variable in your design

B

36

How to usea design pattern

Read the pattern for an overview of its application, consequences, etcStudy the Structure, Participants and Collaborations sectionsLook at the Sample CodeChoose names for participants (classes and methods) that are meaningful in your contextDefine the classes and appropriate interfacesImplement the operations to carry out the responsibilities and collaborations in the pattern

B

37

38

Worked-out example 1:Factory Method

39

Factory Method

Classification: Class Creational

Intent: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses

Motivating example Application for presenting documents to a user

B

40

Factory Method: Motivation

{ Document doc = this.createDocument();doc.open();return doc; }

{ Document doc = this.createDocument();doc.open();return doc; }

{ return new Postscript() }{ return new Postscript() }

Document

open()save()

DocumentViewer

openDocument()newDocument()createDocument()

PSDocumentViewer

createDocument()

Postscript

open()save()

JPEG

open()save()

B

41

Factory Method: Applicability

Use the Factory Method design pattern when: A class can’t anticipate the class of objects it must

create A class wants its subclasses to specify the objects it

creates Classes delegate responsibility to one of several helper

subclasses, and you want to localise the knowledge of which helper classes to use

B

42

Factory Method : Participants

Product (e.g. Document) Defines the interface of objects the factory method creates

ConcreteProduct (e.g. Postscript) Implements the Product interface

Creator (e.g. DocumentViewer) Declares the abstract factory method (createDocument) May call the factory method to create a Product object

ConcreteCreator (e.g. PSDocumentViewer) Overrides factory method with a concrete one to return a

ConcreteProduct instance

B

43

Factory Method: Structure

Product

ConcreteProduct

Creator

factoryMethod()

ConcreteCreator

factoryMethod()

B

create

44

Factory Method: Collaborations

Creator relies on its ConcreteCreator subclassesto specify the concrete factory method so that it returns an instance of the appropriate ConcreteProduct

B

45

Factory Method: Consequences

More reusable than creating objects directly

Connects parallel class hierarchies

Product

ConcreteProductA

Creator

factoryMethod()

ConcreteCreatorA

factoryMethod()

Client

ConcreteCreatorB

factoryMethod()

ConcreteProductB

B

46

Factory Method: Implementation

Variation 1: Some factory methods can provide a default. In that

case the factory method is not abstract.

Variation 2: Factory methods can be parameterised to return

multiple kinds of products. e.g. pass an extra parameter to createDocument to

specify the kind of Document to create.

B

47

48

Worked-out example 2:Builder

49

Builder

Classification: Object CreationalIntent: Separate the construction of a complex object from its internal representation so that the same construction process can create different representationsMotivating example converting RTF-files into different file formats

B

50

Builder: Motivation

while (t = get the next token) { switch t.type { CHAR: builder.convertCharacter(char) FON: builder.convertFontChange(font) PARA: builder.convertParagraph(para) } }

while (t = get the next token) { switch t.type { CHAR: builder.convertCharacter(char) FON: builder.convertFontChange(font) PARA: builder.convertParagraph(para) } }

ASCII-textLaTeX-text

builder TextConverter

convertChar(char)convertFont(Font)convertParagraph()

LaTeXConverter

convertChar(char)convertFont(Font)convertParagraph()getTeXText()

AsciiConverter

convertChar(char)getAsciiText()

RTFReader

parseRTF()

B

51

Builder: Applicability

Use the Builder design pattern when The algorithm for constructing a complex object should

be independent of the parts that make up the object and how they are assembled

The construction process must allow for different representations of the object that is constructed

B

52

Builder: Participants

Product (e.g. Ascii-text, LaTex-text) Represents the complex object under construction

Abstract builder (e.g. TextConverter) Specifies an abstract interface for creating parts of a

Product object

Concrete builder (e.g. AsciiConverter) Constructs and assembles part of the product by

implementing the Builder interface

Director (e.g. RTFReader) Constructs an object using the Builder interface

B

53

Builder: Structure

for(all objects in structure){ builder.buildPart() }

for(all objects in structure){ builder.buildPart() }

Product

builder Builder

buildPart()

ConcreteBuilder

buildPart()Product getResult()

Director

construct()

B

54

Builder: Collaborations

Director notifies the Builder whenever a part of the Product should be built

Builder handles requests from the Director and adds parts to the Product

B

55

Builder: Consequences

Lets you vary a product’s internal representation (e.g. new versions of RTF format)

Isolates code for construction and representation

It gives you finer control over the construction process Step by step construction

B

56

57

Worked-out example 3:Composite

58

Composite

Classification: Object StructuralIntent: Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects in a uniform and transparent wayMotivating example An application for graphical objects

B

59

Composite: Motivation

graphics

for(all g in graphics) { g.draw }

for(all g in graphics) { g.draw }

Graphic

draw()add(Graphic g)

Line

draw()

Text

draw()

Picture

draw()add(Graphic g)

B

*

60

Composite: Applicability

Use the Composite design pattern when You want to represent part-whole hierarchies of

objects You want clients to ignore the difference

between compositions of objects and individual objects

B

61

Composite: Participants

Component (e.g. Graphic) declares the interface for objects in the composition (draw) declares an interface for accessing and managing contained

components (add)

Leaf (e.g. Line, Text) defines behavior for primitive objects in the composition

Composite (e.g. Picture) defines behavior for composite components stores contained components implements access operations in the component interface

B

62

Composite: Structure

for(all g in parts) { g.operation() }

for(all g in parts) { g.operation() }

Component

operation()add(Component)remove(Component)

Leaf

operation()

Composite

operation()add(Component)remove(Component)getComponent(int)

B

*parts

63

Composite: Collaborations

If the recipient of a message is a Leaf, the request is handled directly

If the recipient is a Composite, the request is usually forwarded to contained components, but some additional operations before and/or after the forwarding can happen

B

64

Composite: Consequences

Makes the clients simple No distinction between leafs and composites

Makes it easy to add new kinds of leaf components

Can make the design overly general Hard to restrict the components of a composite

(if we only want to allow certain kinds of a components in a composite)

B

65

Composite: Implementation

Where to put the child management operations (e.g. add, remove) Component (transparency) or Composite (safety)

Data structure to store the componentsBi-directional links Difficult if Components are shared amongst

Composites (cf. aggregation vs composition)

B

66

67

Worked-out example 4:Decorator

68

Decorator

Classification: Object StructuralIntent: Attach additional responsibilities to an object dynamically. Decorators provide a dynamic alternative for subclassingMotivating example adding borders/scrollbars/…

to a visual component

B

69

Decorator: Motivation

component

component.draw()component.draw()

super.draw();drawBorder()

super.draw();drawBorder()

VisualComponent

draw()

TextView

draw()

Decorator

draw()

BorderDecorator

draw()drawBorder()

ScrollDecorator

draw()scrollTo()

B1

70

Decorator: Applicability

Use the Decorator design pattern To add responsibilities to individual objects

dynamically and transparently without affecting other objects

For responsibilities that can be withdrawn When extending by subclassing is impractical

B

71

Decorator: Participants

Component (e.g. VisualComponent) Defines the interface for objects that can have responsibilities

added to them dynamically

ConcreteComponent (e.g. TextView) Defines an object to which we want to attach additional

responsibilities

Decorator (e.g. Decorator) Maintains a reference to a Component object and defines an

interface that conforms to the Components interface

ConcreteDecorator (e.g. BorderDecorator) Adds responsibilities to the component

B

72

ConcreteDecoratorB

added state

operation()

Decorator: Structure

component.operation()component.operation()

super.operation();added behaviour

super.operation();added behaviour

component

Component

operation()

ConcreteComponent

operation()

Decorator

operation()

ConcreteDecoratorA

added state

operation()

B1

73

Decorator: Collaborations

Decorator forwards requests to the Component object. It may optionally perform additional behaviour before and after forwarding the request

B

74

Decorator: Consequences

More flexible than static inheritance Dynamically adding/withdrawing responsibilities

Avoids classes with a lot of features

Lots of little objects

B

75

Decorator: Implementation

Object identity can be a problem a decorated component is not identical to the object

itself

76

77

Worked-out example 5:Strategy

78

Strategy

Classification: Object BehaviouralIntent: Define a family of algorithms and make them interchangeable. Strategy lets the algorithm vary independently from clients that use itMotivating example Different sorting algorithms String search in a text processor

B

79

Strategy: Motivation

searcherSearchAlgorithm

searchFor(String, Text)

SearchAlgorithm2

searchFor(String, Text)

SearchAlgorithm1

searchFor(String, Text)

TextProcessor

text

search(String)

B

1

80

Strategy: Applicability

Use the Strategy pattern when Many related classes that differ only in their behaviour You need different variants of an algorithm An algorithm uses data that clients should not know

about A class defines many behaviours

B

81

Strategy: Participants

Strategy (e.g. SearchAlgorithm) Declares an interface common to all supported

algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy

ConcreteStrategy (e.g. SearchAlgoritm1) Implements the algorithm using the strategy interface

Context (e.g. TextProcessor) Is configured with a ConcreteStrategy object Maintains a reference to a Strategy object May define an interface that lets Strategy access its data

B

82

Strategy: Structure

Strategy

algorithmInterface()

Strategy2

algorithmInterface()

Strategy1

algorithmInterface()

Context

contextInterface()

B

1

83

Strategy: Collaborations

Strategy and Context interact to implement the chosen algorithm Context may pass all data required by the algorithm to the strategy

when the algorithm is called Context can pass itself as an argument to Strategy operations

A Context forwards requests from its clients to its strategy Clients usually create and pass a ConcreteStrategy object to the

Context. From then on, they interact with the Context exclusively.

B

84

Strategy: Consequences

Families of related algorithms

An alternative to subclassing

Strategies eliminate conditionals

Provide a choice of implementation allow for different implementations of same behaviour

Overhead involved Communication between Context and Strategy Increased number of objects

B

85

Strategy: Implementation

The Strategy interface must provide enough information to ConcreteStrategy

Default behaviour can be incorporated in the Context object. If no strategy object is present, this default behaviour can be used.

B

86

87

Worked-out example 6:State

88

State

Classification: Object Behavioral

Intent: Allow an object to dynamically alter its behavior when its internal state changes. The object will appear to change its class.

Motivating example open/closed/maximised/iconised windows network connection

B

89

State: Motivation

state.close()state.close()

stateTCPState

open()close()

Closed

open()close()

Established

open()close()

TCPConnection

open()close()

Listening

open()close()

B

1

90

State: Applicability

Use the State Pattern when an object’s behavior depends on its state and it

must change its behavior at runtime operations have large conditional statements

that depend on the state of the objects

B

91

State: Participants

Context (e.g. TCPConnection) Defines an interface of interest to clients Maintains an instance of a ConcreteState subclass that

defines the current state

State (e.g. TCPState) Defines an abstract interface for encapsulating the

behaviour associated with a particular state of the Context

ConcreteState (e.g. Established, Closed, Listening) Each subclass implements a behaviour associated with

a state of the Context

B

92

State: Structure

state.handle()state.handle()

stateState

handle()

ConcreteState1

handle()

Context

request()

ConcreteState2

handle()

B

93

State: Collaborations

Context delegates state-specific requests to the current ConcreteState objectA Context may pass itself as an argument to the State object handling the requestContext is the primary interface for clients. Once a Context is configured, clients do not deal with the State objects

B

94

State: Consequences

Separates state-specific behavior from general behavior

Makes state-transitions explicit

State objects can be shared

B

95

96

Worked-out example 7:Visitor

97

Visitor

Classification: Object behavioral

Intent: Define operations to be performed on the elements of an object structure. Visitor lets you define new operations without changing the classes of the objects on which it operates

Motivating example: Visiting a program structure: pretty print, type

checking, code generation, …

B

98

Visitor: MotivationVisitor

visitAssignment(AssignmentNode x)visitVariableRef(VariableRefNode x)

TypeCheckingVisitor

visitAssignment(AssignmentNode x)visitVariableRef(VariableRefNode x)

CodeGeneratingVisitor

visitAssignment(AssignmentNode x)visitVariableRef(VariableRefNode x)

AssignmentNode

accept(Visitor v)

Node

accept(Visitor v)

VariableRefNode

accept(Visitor v)

Program

v.visitAssignment(this)v.visitAssignment(this)

v.visitVariableRef(this)v.visitVariableRef(this)

B

99

Visitor: Applicability

Use the Visitor design pattern when Many operations need to be performed on the objects in

an object structure The classes defining the objects rarely change, but you

often want to define new operations on the structure An object structure contains many different classes and

you want to perform operations on the objects that depend on their concrete classes

B

100

Visitor: Participants

Visitor (e.g. NodeVisitor) Declares an abstract visit operation for each ConcreteElement

class in the object structure. The operation’s name and signature identifies the class that sent the visit request

Element (e.g. Node) Defines an accept operation that takes a Visitor as an argument

ConcreteVisitor (e. g. TypeCheckingVisitor) Implements each visit operation declared by Visitor Each visit operation implements a fragment of the algorithm for

the corresponding class in the object structure Provides the context for the algorithm and stores its state (often

accumulating results during traversal)

B

101

Visitor: Participants

ConcreteElement (e.g. AssignmentNode) Implements an accept operation that takes a visitor as an argument

ObjectStructure (e.g. Program) Can enumerate its elements May provide a high-level interface to allow the visitor to visit its

elements May either be a Composite or a collection such as a list or a set

B

102

Visitor: Structure

Visitor

visitElementA(ConcreteElementA x)visitElementB(ConcreteElementB x)

ConcreteVisitorA

visitElementA(ConcreteElementA x)visitElementB(ConcreteElementB x)

ConcreteVisitorB

visitElementA(ConcreteElementA x)visitElementB(ConcreteElementB x)

ConcreteElementA

accept(Visitor v)

Element

accept(Visitor v)

ConcreteElementB

accept(Visitor v)

ObjectStructure

Client

B

103

Visitor: Collaborations

A client that uses the visitor pattern must create a ConcreteVisitor object and then traverse the object structure visiting each element with the visitor

When an element is visited, it calls the Visitor operation that corresponds to its class. The element supplies itself as an argument to this operation

B

104

Visitor: Consequences

Makes adding operations easy

Gathers related operations inside same visitor class

Adding new ConcreteElement classes is hard

Breaking encapsulation Visitors need to access the internal state of the concreteElements,

breaking data encapsulation

B

105

106

Presentation Overview

A. Introduction to Design Patterns

B. Discussion of Design Patterns

C. AntiPatterns Context and definition Example: The Blob

D. Conclusion

107

C. AntiPatterns

108

Main Reference

AntiPatterns:Refactoring Software, Architectures

and Projects in Crisis

W.J. Brown, R.C. Malveau,H.W. McCormick, T.J. Mowbray

John Wiley & Sons, 1997

C

109

What are AntiPatterns?

While design patterns identify good working practices, antipatterns identify common mistakes and how these mistakes can be overcome in refactored solutions.

An AntiPattern is “a commonly used solution to a problem that

generates decidedly negative consequences”

C

110

The 7 Deadly Sins

1. Haste Hasty decisions lead to compromises in SW quality.

Especially testing is a victim. “Just clean up the code, we ship tomorrow…”

2. Apathy Not caring about solving known problems

“Reuse? Who’s ever gonna reuse this crappy code?”

3. Narrow-mindedness Refusal to practice solutions that are widely known to

be effective. “I don’t need to know, and… I don’t care to know”

C

111

The 7 Deadly Sins

4. Sloth (lazyness) Making poor decisions based upon easy answers (lazy

developers)

5. Avarice (greed) The modeling of excessive details, resulting in

overcomplexity due to insufficient abstraction “I’m impressed ! The most complex model ever done !”

6. Ignorance Failing to seek understanding

“100 pages… let’s find a one page summary on the net”

7. Pride Reinventing designs instead of reusing them.

C

112

Categories of AntiPatterns

Development AntiPatterns technical problems/solutions encountered by

programmers

Architectural AntiPatterns identification of common problems in system structures

Managerial AntiPatterns addresses common problems in software processes and

development organizations

C

113

Development Antipatterns

The Blob

Continuous Obsolescence

Lava Flow

Ambiguous Viewpoint

Functional Decomposition

Poltergeists

Golden Hammer

Boat Anchor

Dead End

Spaghetti Code

Minefield Walking

Cut-and-Paste

C

114

Example: The Blob

Category Software Development

Also Known as Winnebago, The God Class

Scale Application

Refactored Solution Name Refactoring of Responsibilities

Root Causes Sloth, Haste

C

115

The Blob: General Form

Designs where one class monopolizes the processing, and other classes primarily encapsulate data Key problem is: majority of responsibilities are

allocated to a single class In general it is a procedural design

conflicts with OO paradigm

C

116

The Blob:Refactored Solution

Refactored Solution Identify or categorize related attributes and

operations Look for ‘natural homes’ for these collections

of functionality Apply OO Design techniques

e.g., inheritance, ...

C

117

AntiPatterns vs Patterns

An AntiPattern is a special kind of design pattern which features an extra refactored solution to the problem.

Context

ForcesPro

blem

Solution

Pattern

Context

ForcesPro

blem

Negative Solution

AntiPattern

Pro

ble

m

Refactored Solution

C

118

119

Presentation Overview

A. Introduction to Design Patterns

B. Discussion of Design Patterns

C. AntiPatterns

D. Conclusion Summary Additional References

120

D. Conclusion

121

Overall Summary …

Design patterns capture successful solutions to recurring problems that

arise during software construction define common vocabulary amongst designers increase reuse of design as opposed to reuse of

implementation help to improve software quality should be used with care! (AntiPatterns)

D

122

Overall Summary …

Design patterns are Smart

provide elegant solutions that a novice would not think of

Generic are independent of specific system or programming

language Well-proven

Have been successfully tested and applied in several real-world applications

D

123

Exercise

Build a simple Calculator application in Java Gradually make it more complex by adding new

functionality Make use of design patterns to keep the design

elegant and reusable

For more information (both exercises and solutions):

See CD-ROM (or contact [email protected])

D

124

Additional References

S. R. Alpert, K. Brown, B. Woolf, 1998. The Design Patterns Smalltalk Companion. Addison-Wesley. K. Beck, 1997. Smalltalk Best Practice Patterns. Prentice Hall. W.J. Brown, H.W. McCormick, S.W. Thomas, 1999. AntiPatterns and Patterns in Software Configuration Management. John Wiley & Sons.F. Buschmann, R. Meunier, H. Rohnert, P. Sommerlad, M. Stal, 1996. Pattern-Oriented Software Architecture: A System of Patterns. John Wiley & Sons.M. Fowler, 1997. Analysis Patterns: Reusable Object Models. Addison-Wesley.

D

125

Additional References ctd.

Martin Fowler, 1999. Refactoring: Improving the Design of Existing Programs. Addison-Wesley.A.J. Riel, 1996. Object-Oriented Design Heuristics. Addison-Wesley.W. Pree, 1995. Design Patterns for Object-Oriented Software Development. Addison-Wesley.J.O. Coplien, D.C. Schmidt, 1995. Pattern Languages of Program Design. Addison-Wesley.J.M. Vlissides, J.O. Coplien, N. Kerth, 1996. Pattern Languages of Program Design 2. Addison-Wesley.R.C. Robert, D. Riehle, F. Buschmann, J. Vlissides, 1997. Pattern Languages of Program Design 3. Addison-Wesley.

D