0% found this document useful (0 votes)
7 views

SE05 Design Patterns

asdfasdf

Uploaded by

bharathvenna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

SE05 Design Patterns

asdfasdf

Uploaded by

bharathvenna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

6/11/21

Design Patterns

Object Oriented Programming

http://softeng.polito.it/courses/09CBI
Version 3.8.0
© Marco Torchiano, 2020

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

Licensing Note
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.
2

1
6/11/21

Pattern

A reusable solution
to a known problem
in a well defined context

…just one of the possible definitions

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

2
6/11/21

Example

§ Context:
w At the supermarket several customers crowd the
gastronomy desk to get their fresh cut of ham
§ Problem:
w Customers quarrel to have their turn first
w Order of arrival should be obeyed
w It is hard to spot who arrived earlier or later
§ Solution:
w Provide numbered tickets the customer take as
soon as they arrive and which they are called by

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 …

3
6/11/21

Types of Pattern
§ Architectural Patterns
w Address system wide structures
§ Design Patterns
w Leverage higher level mechanisms
§ Idioms
w Leverage language specific features

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

4
6/11/21

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

Design pattern
§ Provides a scheme for refining
components of a software system or
their relationships
§ Describes a commonly recurring
structure of communicating
components

10

10

5
6/11/21

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

11

11

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

12

12

6
6/11/21

Example
§ Context:
w An attribute is constant and should be
globally available to many classes
§ Problem:
w Opening access would allow unauthorized
modifications
w The attribute is repeated in every object
§ Solution:
w Make it public static final

13

13

Pattern Description
§ Name
§ Problem § Name
§ Context § Intent
§ Motivation
§ Forces
§ Applicability
§ Solution
§ Structure
§ Force Resolution § Participants
§ Design Rationale § Collaborations
§ Consequences
§ Implementation
§ Related Patterns
14

14

7
6/11/21

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

15

15

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

16

16

8
6/11/21

Example
§ MVC is implemented using
w Observer
w Iterator

17

17

Design Patterns (GoF)


§ Describe the structure of components
§ Most widespread category of pattern
§ First category of patterns proposed for
software development

18

18

9
6/11/21

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

19

19

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

20

10
6/11/21

Description
§ Name and classification
§ Intent
w Also known as
§ Motivation
§ Applicability
§ Structure
§ Participants
§ Collaborations
§ Consequences
§ Implementation
§ Sample code
§ Known uses
§ Related patterns

21

21

Pattern classification
§ Purpose
w Creational
w Structural
w Behavioral
§ Scope
w Class
w Object

22

22

11
6/11/21

Pattern classification

Purpose
Creational Structural Behavioral

Class 1 1 2
Scope

Object 4 6 10

23

23

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

24

24

12
6/11/21

Using a pattern
§ Read through the pattern
§ Go back and study
w Structure
w Participants
w Collaborations
§ Look at the sample code

25

25

Using a pattern
§ Choose names for participants
w Meaningful in the application context
§ Define the classes
§ Choose operation names
w Application specific
§ Implement operations

26

26

13
6/11/21

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

27

27

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

28

28

14
6/11/21

Abstract Factory Example

Client

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

WindowVista WindowOSX
ConcreeFactoryVista ConcreeFactoryOSX
#Operation(i: int): int #Operation(i: int): int
/+createWindow() /+createWindow() creates
/+createButton() /+createButton()
... ...

creates

29

29

Abstract Factory

Client

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

ConcreteProductAX ConcreteProductAY
ConcreeFactoryX ConcreeFactoryY
#Operation(i: int): int #Operation(i: int): int
/+createProductA() /+createProductA() creates
/+createProductB() /+createProductB()
... ...

creates

30

30

15
6/11/21

Singleton
§ Context:
w A class represents a concept that requires
a single instance
§ Problem:
w Clients could use this class in an
inappropriate way

31

31

Singleton Pattern
Singleton
Singleton class
-Singleton()
+getInstance(): Singleton
singletonOperation() Instantiation
static method

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

32

32

16
6/11/21

Singleton Example
§ java.awt.Toolkit
w Singleton + FactoryMethod

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

33

33

Builder object
§ Context
w An object of a complex class has to be
created
§ Problem
w The creation entails complex interaction
with the object
w Different variation of the target object
might be created

34

34

17
6/11/21

Builder Pattern 2020/0


pkg builder

Builder Pattern

Builder ConcreteBuilder
Director
+ buildPart() : void + buildPart() : void

<<create>>

Product

35

35

Builder Example 2020/03/31


pkg builder

Builder example
Abstract Builder Concrete Builder

<<interface>>
StringBuilder
Client Appendable
+ append() : Appendable
+ append() : Appendable

<<create>>
Director

String

Complex object

36

36

18
6/11/21

Example Measure builder


Builder Measure 2020/03/31
pkg builder Builder
Complex object

Builder
Measure
+ is() : Builder
+ by() : Builder
+ build() : Builder
+ squared() : Builder object
0..1 1 + addUnit() : void
+ to() : Builder
+ setPrecision() : void
+ withPrecision() : Builder
+ done() : Measure

Note: Simplified version w.r.t. GoF

37

37

Structural patterns
§ Structural patterns are concerned with
how classes and objects are composed
to form larger structures.

38

38 1/1

19
6/11/21

GoF structural patterns


§ Adapter
§ Bridge
§ Composite
§ Decorator
§ Facade
§ Flyweight
§ Proxy

39

39

Adapter
§ Context:
w A class provides the features required by
another class but its interface is not the
one expected
§ Problem:
w The integration of the provider class
should be possible without modifying it
– Its source code could be not available
– It is already used as it is somewhere else

40

40

20
6/11/21

Adapter

Target
Client
Request()
Adaptee
adaptee SpecificRequest()

Adapter
Request()

41

41

Adapter example

DrawingEditor Shape
BoundingBox()
CreateManipulator()
TextView
GetExtent()

Line TextShape
BoundingBox() BoundingBox()
CreateManipulator() CreateManipulator()

42

42

21
6/11/21

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

43

43

Java Listener Adapter


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

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

44

44

22
6/11/21

Java Listener Adapter


jawa.awt.event java.awt

«interface»
KeyListener use
JFrame
KeyPressed()
KeyReleased()
KeyTyped()
Extends
KeyAdapter
Implements KeyPressed()
KeyReleased()
KeyTyped()
MyFrame

Extends

MyListener
KeyReleased()

45

45

Structural Class Patterns


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

46

46

23
6/11/21

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.

47

47

Composite

Client Component
child
operation()
add(Component ) 0..*
remove(Component )
getChild()

Leaf Composite
operation() operation()
add(Component )
remove(Component )
getChild()

48

48

24
6/11/21

Composite Example
§ Arithmetic expressions representation
w Operators
w Operands
§ Evaluation of expressions

49

49

Composite Example

Calculator Expression
operands
evaluate()
print() 0..*

Value Operation
evaluate() op: String
print() evaluate()
print()

50

50

25
6/11/21

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

51

51

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);
}
}

52

52

26
6/11/21

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;
}

53

53

Composite Example
class Operation {

public evaluate(){
switch(op){
case ‘+’: return
left.evaluate() +
right.evaluate();
break;

}
}

54

54

27
6/11/21

Composite Example
class Operation {

public print(){
return left.print() + op +
right.print();
}
}

55

55

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

56

56

28
6/11/21

Facade

Client

Facade

57

57

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.

58

58

29
6/11/21

GoF behavioral patterns


Object-level Class-level
w Chain of w Template Method
Responsibility w Interpreter
w Command
w Iterator
w Mediator
w Memento
w Observer
w State
w Strategy
w Visitor

59

59

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

60

60

30
6/11/21

Encapsulating Variation
§ A varying aspect of a program
§ Captured by an object
w Other delegate operations to the “variant”
object

61

61

Argument Objects
§ Often an object is passed as argument
w Hides complexity from clients
w Concentrate the “active” code in one class

62

62

31
6/11/21

Information circulation
§ Responsibility of how to circulate
information may be:
w Distributed among different parties.
w Encapsulated in a single object.

63

63

Communication decoupling
§ Decoupling senders and receivers is a
key to:
w Reduce coupling
w Improve reusability
w Enforce layering and structure

64

64

32
6/11/21

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

65

65

Observer

Subject
attach(Observer) Observer
observers
detach(Observer) update()
0..*
notify()

ConcreteSubject
- state ConcreteObserver
getState() update()
setState()

66

66

33
6/11/21

Observer - Consequences
+ Abstract coupling between Subject
and Observer
+ Support for broadcast communication
- Unanticipated updates

67
67

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

68

34
6/11/21

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

java.util

Observable
Observer
+ addObserver() : void
+ update() : void notifies + setChanged() : void
+ notifyObservers() : void

UnitObserver Task

+ update() : void + longRunningTask() : void

tasks

69

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

70

70

35
6/11/21

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)

71

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

72

36
6/11/21

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

73

Concerned + Subject 2020/03/29


pkg observer

Inheritance vs. Composition


Observable
<<interface>>
Observer
+ addObserver() : void
notifies + setChanged() : void
+ update() : void
+ notifyObservers() : void

Inheritance
Concerned + Subject (composition) 2020/03/29
Concerned Subject
pkg ObserverComposition
- prop : String
+ update() : void
+ setProp() : void

<<interface>> PropertyChangeSupport
PropertyChangeListener
notifies + addPropertyChangeListener() : void
+ propertyChange() : void + firePropertyChange() : void

1 Composition
Concerned Subject
- prop : int
+ propertyChange() : void
+ setProp() : void
+ addListener() : void

74

74

37
6/11/21

Observer w/Inheritance
S+C inheritance
sd S+C inheritance
2020/03/29

client subject : Subject concerned : Concerned

1: addObserver() : void

2: setProp() : void 2.1: setChanged() : void

2.2: notifyObservers() : void

2.2.1: update() : void

75

75

C+S composition
Observer w/Composition
sd C+S composition
2020/03/29

client subject : Subject support : PropertyChangeSupport concerned : Concerned

1: addListener() : void
1.1: addPropertyChangeListener() : void

2: setProp() : void
2.1: firePropertyChange() : void
2.1.1: propertyChange() : void

1/1

76

76

38
6/11/21

Observer subject w/inheritance


public class Subject
extends Observable {

String prop="ini";

public void setProp(String val){


setChanged();
property = val;
notifyObservers("theProp");
}

}
77

77

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);
} }
78

78

39
6/11/21

Observer with inheritance


public class Concerned
implements Observer {

@Override
public void update(Observable src,
Object arg) {
System.out.println("Variation of " +
arg);
}

79

79

Observer with composition


public class Concerned
implements PropertyChangeListener {

@Override
public void propertyChange(
PropertyChangeEvent evt) {
System.out.println("Variation of " +
evt.getPropertyName());
}

80

80

40
6/11/21

Observer Example
/01234231#
!"#$%
!"#$% .$+#
($+#
-$+#
*$+#
&$+#
,$+#
$+#
!# '# )#

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

81

81

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

82

82

41
6/11/21

Template Method
Core algorithm, invokes abstract
primitive operations
AbstractClass
templateMethod()
primitiveOperation() ...
primitiveOperation()
...
primitiveOperation()
...
ConcreteClass
primitiveOperation()

Defines a variation of the


algorithm

83

83

Template Method Example

Sorter
sort(Object)
compare()

IntegerSorter
compare()

84

84

42
6/11/21

Example: Sorter
public abstract class Sorter {
public void sort(Object v[]){
for(int i=1; i<v.length; ++i)
for(int j=0; j<v.length-i; ++j){
if(compare(v[j],v[j+1])>0){
Object o=v[j];
v[j]=v[j+1]; v[j+1]=o;
} } }
}
abstract int compare(Object a, Object b);
}

85

85

Example: StringSorter
class StringSorter extends Sorter {
int compare(Object a, Object b){
String sa=(String)a;
String sb=(String)b;
return sa.compareTo(sb);
}
}
Sorter ssrt = new StringSorter();
String[] v={"g","t","h","n","j","k"};
ssrt.sort(v);

86

86

43
6/11/21

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.

87

87

Strategy

Context Strategy
ContextInterface() algorithmInterface()

ConcreteStrategyA ConcreteStrategyB
algorithmInterface() algorithmInterface()

88

88

44
6/11/21

Strategy example: Comparator

Collections «Interface»
sort() Comparator
compare(Object a, Object b)

StringComparator IntegerComparator
compare() compare()

89

89

Comparator
– Interface java.util.Comparator

public interface Comparator<T>{


int compare(T a, T 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

90

90

45
6/11/21

Comparator
class StudentCmp
implements Comparator<Student>{
public int compare(Student a,Student b){
return a.id – b.id;
}
}

Student[] sv = { new Student(11),


new Student(3),
new Student(7)};
Arrays.sort(sv, new StudentCmp());

91

91

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

92

92

46
6/11/21

Iterator pattern
§ Context
w A collection of objects must be iterated
§ Problem
w Multiple concurrent iterations are possible
w The internal storage must not be exposed
§ Solution
w Provide an iterator object, attached to the
collection, that can be advanced
independently

93

93

Class Diagram0 2020/04/02

Iterator pattern
pkg iterator

<<interface>>
<<interface>>
Iterator
Aggregate <<create>>
+ next() : Object
+ iterator() : Iterator
+ hasNext() : boolean

<<create>> ConcreteIterator
ConcreteAggregate
+ next() : Object
+ iterator() : Iterator
+ hastNext() : boolean
refers to

94

94

47
6/11/21

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

95

95

Visitor
Visitor
Client viewElemA(ConcreteElemA)
ViewElemB(ConcreteElemB)

ConcreteVisitor1 ConcreteVisitor2
viewElemA(ConcreteElemA) viewElemA(ConcreteElemA)
viewElemB(ConcreteElemB) viewElemB(ConcreteElemB)

Element
accept(Visitor)

ConcreteElemA ConcreteElemB
accept(Visitor) accept(Visitor)

96

96

48
6/11/21

Visitor Example
StatementVisitor
Compiler visitAssignment(Assignment)
visitReference(Reference)

TypeCheckingVisitor CodeGenerationVisitor
visitAssignment(Assignment) visitAssignment(Assignment)
visitReference(Variable) visitReference(Reference)

Statement
accept(Visitor)

Assignment Reference
accept(Visitor) accept(Visitor)

97

97

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

98

98

49
6/11/21

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

99

99

50

You might also like