design patterns - oop · design patterns § description of communicating objects and classes that...

45
Design Patterns Object Oriented Programming http://softeng.polito.it/courses/09CBI Version 3.6.0 © Marco Torchiano, 2018 This work is licensed under the Creative Commons Attribution- NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/ . You are free: to copy, distribute, display, and perform the work Under the following conditions: Attribution. You must attribute the work in the manner specified by the author or licensor. Non-commercial. You may not use this work for commercial purposes. No Derivative Works. You may not alter, transform, or build upon this work. § For any reuse or distribution, you must make clear to others the license terms of this work. § Any of these conditions can be waived if you get permission from the copyright holder. Your fair use and other rights are in no way affected by the above.

Upload: others

Post on 15-Jul-2020

14 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Design Patterns

Object Oriented Programming

http://softeng.polito.it/courses/09CBI

Version 3.6.0 © Marco Torchiano, 2018

2

Licensing Note

This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/. You are free: to copy, distribute, display, and perform the work

Under the following conditions: §  Attribution. You must attribute the work in the manner specified by

the author or licensor.

§  Non-commercial. You may not use this work for commercial purposes.

§  No Derivative Works. You may not alter, transform, or build upon this work.

§  For any reuse or distribution, you must make clear to others the license terms of this work.

§  Any of these conditions can be waived if you get permission from the copyright holder.

Your fair use and other rights are in no way affected by the above.

Page 2: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

3

Pattern

A reusable solution to a known problem

in a well defined context

…just one of the possible definitions

4

Pattern §  Context

w  A (design) situation giving rise to a (design) problem

§  Problem w  Set of forces repeatedly arising in the context

–  Force: any relevant aspect of the problem (Eg. requirements, constraints, desirable properties)

§  Solution w  A proven resolution of the problem w  Configuration to balance forces

–  Structure with components and relationships –  Run-time behaviour

Page 3: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

5

Example §  Context:

w You are in a crowded pub to get a beer §  Problem:

w Other people are waiting in front of you w You want to get the beer asap w You don’t want to start a fight

§  Solution: w Try to spot the last person in the line w You enter the line after her/him

6

History §  Initially proposed by Chrisopher

Alexander §  He described patterns for architecture

(of buildings) w The pattern is, in short, at the same time

a thing, which happens in the world, and the rule which tells us how to create that thing and when we create it. It is both a process and a thing …

Page 4: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

7

Types of Pattern §  Architectural Patterns

w Address system wide structures §  Design Patterns

w Leverage higher level mechanisms §  Idioms

w Leverage language specific features

8

Architectural pattern §  Expresses a fundamental structural

organization schema for software systems

§  Provides a set of predefined components with their responsibilities

§  Defines the rules and guidelines for organizing the relationships between the components

Page 5: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

9

Example §  Context:

w  several programs that are used in sequence read from input and write sequentially to output

§  Problem: w  there are a lot of intermediate files used for

communication between programs §  Solution:

w  adopt a pipe & filter architecture feeding a program with the result of the previous one

10

Design pattern §  Provides a scheme for refining

components of a software system or their relationships

§  Describes a commonly recurring structure of communicating components

Page 6: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

11

Example §  Context:

w  A class library providing few functionalities contains a lot of classes

§  Problem: w  The user is exposed to the internal complexity of

the library §  Solution:

w  Create a new façade class that interacts with the user and hide all the details

12

Idiom §  Is a low-level pattern specific to a

programming language §  Describes how to implement particular

aspects of components or the relationships between them

§  Leverages the features of a programming language

Page 7: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

13

Example §  Context:

w two classes, very similar except some details

§  Problem: w double effort in maintenance

§  Solution: w create a generic containing the common

parts, and make the classes derive from it.

14

Pattern Description §  Name §  Problem §  Context §  Forces §  Solution §  Force Resolution §  Design Rationale

§  Name §  Intent §  Motivation §  Applicability §  Structure §  Participants §  Collaborations §  Consequences §  Implementation §  Related Patterns

Page 8: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

15

Pattern language §  Pattern do not exist in isolation

w Two or more patterns are applied together

w A pattern is used to implement part of another pattern

w A pattern can introduce a problem solved by another

§  We have Pattern Languages w Or pattern systems

16

Pattern Language §  Collection of patterns together with

guidelines for w Implementation w Combination w Practical use

§  Should w Count enough patterns w Describe patterns uniformly w Present relationships

Page 9: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

17

Example §  MVC is implemented using

w Observer w Iterator

18

Design Patterns (GoF) §  Describe the structure of components §  Most widespread category of pattern §  First category of patterns proposed for

software development

Page 10: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

19

Design Patterns (GoF) §  Creational

w E.g. Abstract Factory, Singleton §  Structural

w E.g. Façade, Composite §  Behavioral

w Class: e.g. Template Method w Object: e.g. Observer

Design patterns §  Description of communicating objects

and classes that are customized to solve a general design problem in a particular context

§  A design pattern names, abstracts, and identifies the key aspects of a common design structure that make it useful for creating a reusable object-oriented design

20

Page 11: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Description §  Name and classification §  Intent

w Also known as §  Motivation §  Applicability §  Structure §  Participants §  Collaborations

21

Description §  Consequences §  Implementation §  Sample code §  Known uses §  Related patterns

22

Page 12: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Classification §  Purpose

w Creational w Structural w Behavioral

§  Scope w Class w Object

23

Classification

Purpose

Creational Structural Behavioral

Scop

e Class 1 1 2

Object 4 6 10

24

Page 13: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Pattern selection §  Consider how patterns solve problems §  Scan intent sections §  Study how pattern interrelate §  Study patterns of like purpose §  Examine a cause of redesign §  Consider what should be variable in

your design

25

Using a pattern §  Read through the pattern §  Go back and study

w Structure w Participants w Collaborations

§  Look at the sample code

26

Page 14: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Using a pattern §  Choose names for participants

w Meaningful in the application context §  Define the classes §  Choose operation names

w Application specific §  Implement operations

27

Creational patterns §  Factory Method §  Abstract Factory §  Builder §  Prototype §  Singleton

28

Page 15: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

29

Abstract Factory §  Context

w A family of related classes can have different implementation details

§  Problem w The client should not know anything

about which variant they are using / creating

30

Abstract Factory Example

Client

WidgetFactory#Operation(i: int): int/+createWindow()/+createButton()...

ConcreeFactoryVista#Operation(i: int): int/+createWindow()/+createButton()...

ConcreeFactoryOSX#Operation(i: int): int/+createWindow()/+createButton()...

AbstractWindow

WindowVista WindowOSX

creates

creates

Page 16: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

31

Abstract Factory

Client

AbstractFactory#Operation(i: int): int/+createProductA()/+createProductB()...

ConcreeFactoryX#Operation(i: int): int/+createProductA()/+createProductB()...

ConcreeFactoryY#Operation(i: int): int/+createProductA()/+createProductB()...

AbstractProductA

ConcreteProductAX ConcreteProductAY

creates

creates

32

Singleton §  Context:

w A class represents a concept that requires a single instance

§  Problem: w Clients could use this class in an

inappropriate way

Page 17: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Singleton-Singleton()+getInstance(): SingletonsingletonOperation()

33

Singleton Singleton

class

Instantiation static method

private Singleton() { } private static Singleton instance; public static Singleton getInstance(){ if(instance==null) instance = new Singleton(); return instance; }

Singleton Example §  java.awt.Toolkit

w Singleton + FactoryMethod

java.awt::Toolkit-Toolkit()+getDefaultToolkit(): Toolkit...

34

Page 18: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Structural patterns §  Structural patterns are concerned with

how classes and objects are composed to form larger structures.

35

GoF structural patterns §  Adapter §  Bridge §  Composite §  Decorator §  Facade §  Flyweight §  Proxy

36

Page 19: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

37

Adapter §  Context:

w A class provides the required features but its interface is not the one required

§  Problem: w How is it possible to integrate the class

without modifying it –  Its source code could be not available –  It is already used as it is somewhere else

38

Adapter

ClientTarget

Request()

AdapterRequest()

AdapteeSpecificRequest()adaptee

Page 20: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

39

Adapter example

DrawingEditor ShapeBoundingBox()CreateManipulator()

LineBoundingBox()CreateManipulator()

TextViewGetExtent()

TextShapeBoundingBox()CreateManipulator()

Java Listener Adapter §  In Java GUI events are handled by

Listeners §  Listener classes need to implement

Listener interfaces w Include several methods w They all should be implemented

40

Page 21: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Java Listener Adapter class MyListener{ public void KeyPressed(..){} public void KeyReleased(..){ // … handle event } public void KeyTyped(..){} }

class MyListener{ public void KeyReleased(..){ // … handle event } }

41

Java Listener Adapter

«interface»KeyListener

KeyPressed()KeyReleased()KeyTyped()

KeyAdapterKeyPressed()KeyReleased()KeyTyped()

Implements

jawa.awt.event

MyListenerKeyReleased()

Extends

MyFrame

use JFrame

Extends

java.awt

42

Page 22: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Structural Class Patterns §  Adapter pattern

w Inheritance plays a fundamental role w Only example of structural class pattern

43

44

Composite §  Context:

w You need to represent part-whole hierarchies of objects

§  Problem w Clients are complex w Difference between composition objects

and individual objects.

Page 23: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

45

Composite

Client Componentoperation()add(Component )remove(Component )getChild()

Compositeoperation()add(Component )remove(Component )getChild()

Leafoperation()

0..*child

Composite Example §  Arithmetic expressions representation

w Operators w Operands

§  Evaluation of expressions

46

Page 24: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Composite Example

Calculator Expressionevaluate()print()

Operationop: Stringevaluate()print()

Valueevaluate()print()

0..*operands

47

Composite Example abstract class Expression { public abstract int evaluate(); public abstract String print(); }

48

Page 25: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Composite Example class Value { private int value; public Value(int v){ value = v; } public int evaluate(){ return value;

} public String print(){ return new String(value); } }

49

Composite Example class Operation { private char op; // +, -, *, / private Expression left, right public Operation(char op, Expression l, Expression r){

this.op = op; left = l; right= r; } …

50

Page 26: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Composite Example class Operation { … public evaluate(){ switch(op){ case ‘+’: return left.evaluate() + right.evaluate(); break;

… } } …

51

Composite Example class Operation { … public print(){ return left.print() + op + right.print();

} }

52

Page 27: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

53

Facade §  Context

w A functionality is provided by a complex group of classes (interfaces, associations, etc.)

§  Problem w How is it possible to use the classes

without being exposed to the details

54

Facade

Client

Facade

Page 28: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Behavioral patterns §  Behavioral patterns are concerned with

algorithms and the assignment of responsibilities between objects.

§  Not just patterns of objects or classes but also the patterns of communication. w Complex control flow that's difficult to follow

at run-time. w Shift focus away from flow of control to let

concentrate just on the way objects are interconnected.

55

GoF behavioral patterns Object-level

w Chain of Responsibility

w Command w Iterator w Mediator w Memento w Observer w State w Strategy w Visitor

Class-level w Template Method w Interpreter

56

Page 29: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Mechanisms §  Encapsulating variation §  Objects as arguments §  Information circulation policies §  Sender and Receiver decoupling

57

Encapsulating Variation §  A varying aspect of a program §  Captured by an object

w Other delegate operations to the “variant” object

58

Page 30: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Argument Objects §  Often an object is passed as argument

w Hides complexity from clients w Concentrate the “active” code in one class

59

Information circulation §  Responsibility of how to circulate

information may be: w Distributed among different parties. w Encapsulated in a single object.

60

Page 31: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Communication decoupling §  Decoupling senders and receivers is a

key to: w Reduce coupling w Improve reusability w Enforce layering and structure

61

62

Observer §  Context:

w The change in one object may influence one or more other objects

§  Problem w High coupling w Number and type of objects to be notified

may not be known in advance

Page 32: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

63

Observer

Subjectattach(Observer)detach(Observer)notify()

ConcreteSubject- stategetState()setState()

Observerupdate()0..*

observers

ConcreteObserverupdate()

Observer - Consequences + Abstract coupling between Subject and

Observer + Support for broadcast communication - Unanticipated updates

64

Page 33: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Observer-Observable §  Allow a standardized interaction

between an objects that needs to notify one or more other objects

§  Defined in package java.util §  Class Observable §  Interface Observer

Observer-Observable Class Diagram0 2016/03/02 powered by Astah

+ update() : void

Observer

+ notifyObservers() : void+ setChanged() : void+ addObserver() : void

Observable

+ update() : void

UnitObserver

notifies

+ longRunningTask() : void

Task

java.util

tasks

Page 34: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Java Observer-Observable class Observable{ void addObserver(..){} void deleteObserver(..){} void deleteObservers(){} int countObservers() {} void setChanged() {} void clearChanged() {} boolean hasChanged() {} void notifyObservers() {} void notifyObservers(..) {} }

67

Observer-Observable §  Class Observable manages:

w  registration of interested observers by means of method addObserver()

w  sending the notification of the status change to the observer(s) together with additional information concerning the status (event object).

§  Interface Observer allows: w  Receiving standardized notification of the

observer change of state through method update() accepts two arguments:

–  Observable object that originated the notification –  additional information (the event object)

Page 35: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Observer-Observable §  Sending a notification from an

observable element involves two steps: w record the fact the the status of the

Observable has changed, by means of method setChanged(),

w send the actual notification while providing the additional information (the event object), by means of method notifyObservers()

Inheritance vs. composition Reuse can be achieved via: §  Inheritance

w The reusing class has the reused methods available as own methods.

w Clients can invoke directly inherited methods §  Composition

w The reusing class has the reused methods available in an included object (attribute)

w The reusing class must provide methods that accept clients requests and delegate to the included object

Page 36: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Observer subject w/inheritance public class Subject extends Observable {

String prop="ini";

public void setProp(String val){ setChanged(); property = val; notifyObservers("theProp"); } }

Observer subject w/composition public class Subject { PropertyChangeSupport pcs = new PropertyChangeSupport(this);

String prop=”ini";

public void setProp(String val) { String old = property; property = val; pcs.firePropertyChange("theProp”,old,val); } // delegation: public void addObs(PropertyChangeListener l){ pcs.addPropertyChangeListener("theProp”,l); } }

Page 37: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Observer with inheritance public class Concerned implements Observer {

@Override public void update(Observable src, Object arg) {

System.out.println("Variation of " + arg); }

}

Observer with composition public class Concerned implements PropertyChangeListener { @Override public void propertyChange( PropertyChangeEvent evt) {

System.out.println("Variation of " + evt.getPropertyName()); }

}

Page 38: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Composition

75

ConcernedSubject

+ prop : string

+ addObserver(in listener: PropertyChangeListener)+ setProp()

PropertyChangeSupport

PropertyChangeListener

PropertyChangeEvent

<<use>>

1

1+ pcs

+ listeners

*0..1

<<access>>

76

Observer Example !"#$%

!"#$%&#'"#$%(#)#"#$%*#

$+#

,$+#

&$+#

*$+#

-$+#

($+#

.$+#

!# '# )#

!"#$%/01234231#

5607289#

Page 39: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

77

Template Method §  Context:

w An algorithm/behavior has a stable core and several variation at given points

§  Problem w You have to implement/maintain several

almost identical pieces of code

AbstractClasstemplateMethod()primitiveOperation()

ConcreteClassprimitiveOperation()

...primitiveOperation()...primitiveOperation()...

78

Template Method Core algorithm, invokes abstract

primitive operations

Define a variant of the

algorithm

Page 40: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Template Method Example

Sortersort(Object)compare()

IntegerSortercompare()

79

Strategy §  Context

w Many classes or algorithm has a stable core and several behavioral variations

§  Problem w Several different implementations are

needed. w Multiple conditional constructs tangle the

code.

80

Page 41: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Strategy

StrategyalgorithmInterface()

ConcreteStrategyAalgorithmInterface()

ConcreteStrategyBalgorithmInterface()

ContextContextInterface()

81

Strategy Example

«Interface»Comparator

compare(Object a, Object b)

StringComparatorcompare()

IntegerComparatorcompare()

Collectionssort()

82

Page 42: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Comparator §  Interface java.util.Comparator public interface Comparator{ int compare(Object a, Object b); }

§  Semantics (as comparable): returns w a negative integer if a precedes b w 0, if a equals b w a positive integer if a succeeds b

83

Note: simplified version, actual declaration uses generics

Strategy Consequences + Avoid conditional statements + Algorithms may be organized in families + Choice of implementations + Run-time binding - Clients must be aware of different

strategies - Communication overhead - Increased number of objects

84

Page 43: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Visitor §  Context

w An object structure contains many classes with differing interfaces.

w Many different operations need to be performed on the objects

§  Problem w The operations on the objects depend on

their concrete classes w Classes could be polluted with several

operations

85

Visitor Visitor

viewElemA(ConcreteElemA)ViewElemB(ConcreteElemB)

ConcreteVisitor1viewElemA(ConcreteElemA)viewElemB(ConcreteElemB)

ConcreteVisitor2viewElemA(ConcreteElemA)viewElemB(ConcreteElemB)

ConcreteElemBaccept(Visitor)

ConcreteElemAaccept(Visitor)

Elementaccept(Visitor)

Client

86

Page 44: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

Visitor Example StatementVisitor

visitAssignment(Assignment)visitReference(Reference)

TypeCheckingVisitorvisitAssignment(Assignment)visitReference(Variable)

CodeGenerationVisitorvisitAssignment(Assignment)visitReference(Reference)

Referenceaccept(Visitor)

Assignmentaccept(Visitor)

Statementaccept(Visitor)

Compiler

87

Visitor Consequences + Adding new operations is very easy + Behavior is partitioned + Can visit class hierarchies + State can be accumulated - Difficult to add new concrete elements - Break of encapsulation

88

Page 45: Design Patterns - OOP · Design patterns § Description of communicating objects and classes that are customized to solve a general design problem in a particular context § A design

References § M.Fowler, K. Scott, UML Distilled, 3rd

ed. Addison-Wesley, 2003. §  E. Gamma, R. Helm, R. Johnson, and J.

Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software. Reading, MA: Addison-Wesley, 1995.

§  E.Freeman, E.Freeman, K.Sierra, B.Bates. Head First Design Patterns, O’Reilly, 2004

89