52
A LIGHTWEIGHT INTRODUCTION DESIGN PATTERNS hugo sereno ferreira . joão pascoal faria . jorge barbosa . nuno flores

Design Patterns: A Lightweight Introduction

Embed Size (px)

Citation preview

Page 1: Design Patterns: A Lightweight Introduction

A LIGHTWEIGHT INTRODUCTION

DESIGN PATTERNShugo sereno ferreira . joão pascoal faria . jorge barbosa . nuno flores

Page 2: Design Patterns: A Lightweight Introduction

ARCHITECTURE

... a cabana seems simple ...

Page 3: Design Patterns: A Lightweight Introduction

ARCHITECTURE

... easier than an house ...

Page 4: Design Patterns: A Lightweight Introduction

ARCHITECTURE

... child’s play next to a building ...

Page 5: Design Patterns: A Lightweight Introduction

ARCHITECTURE

... but nothing compared to a city!

Page 6: Design Patterns: A Lightweight Introduction

WHERE’S THE DIFFERENCES?

• Size. From a small cabana, to a large city.

• Cost. From less than €1k, to more than €1.000.000k

• Time. Taking a day, to evolving through centuries.

• Process. Doing as an hobby v.s. planning.

• Skills. From a layman, to highly qualified professionals.

• Risk. Vacations v.s. a population of millions.

• ...

Page 7: Design Patterns: A Lightweight Introduction

cost

quality

scope

time

––

– +

+

FINDING THE BEST DESIGN

Page 8: Design Patterns: A Lightweight Introduction

Architecture is the process and product of planning, designing and constructing physical form, space and ambience that reflect functional, technical, social, and aesthetic considerations.

Wikipedia

DEFINITION

Page 9: Design Patterns: A Lightweight Introduction

... the process and product of planning, designing and constructing logical form, space and ambience that reflect functional, technical, social, and aesthetic considerations.

SOFTWARE?

Page 10: Design Patterns: A Lightweight Introduction

QUALITY IN SOFTWARE✦ accessibility

✦ accountability

✦ accuracy

✦ adaptability

✦ administrability

✦ affordability

✦ agility

✦ auditability

✦ availability

✦ credibility

✦ standards compliance

✦ process capabilities

✦ compatibility

✦ composability

✦ configurability

✦ correctness

✦ customizability

✦ degradability

✦ demonstrability

✦ dependability

✦ deployability

✦ distributability

✦ durability

✦ evolvability

✦ extensibility

✦ fidelity

✦ flexibility

✦ installability

✦ integrity

✦ interchangeability

✦ interoperability

✦ learnability

✦ maintainability

✦ manageability

✦ mobility

✦ modularity

✦ nomadicity

✦ operability

✦ portability

✦ precision

✦ predictability

✦ recoverability

✦ relevance

✦ reliability

✦ repeatability

✦ reproducibility

✦ responsiveness

✦ reusability

✦ robustness

✦ safety

✦ scalability

✦ seamlessness

✦ serviceability

✦ securability

✦ simplicity

✦ stability

✦ survivability

✦ sustainability

✦ tailorability

✦ testability

✦ timeliness

✦ understandability

✦ usability

✦ ...

Page 11: Design Patterns: A Lightweight Introduction

OBJECTIVE ATTRIBUTES✦ accessibility

✦ accountability

✦ accuracy

✦ adaptability

✦ administrability

✦ affordability

✦ agility

✦ auditability

✦ availability

✦ credibility

✦ standards compliance

✦ process capabilities

✦ compatibility

✦ composability

✦ configurability

✦ correctness

✦ customizability

✦ degradability

✦ demonstrability

✦ dependability

✦ deployability

✦ distributability

✦ durability

✦ evolvability

✦ extensibility

✦ fidelity

✦ flexibility

✦ installability

✦ integrity

✦ interchangeability

✦ interoperability

✦ learnability

✦ maintainability

✦ manageability

✦ mobility

✦ modularity

✦ nomadicity

✦ operability

✦ portability

✦ precision

✦ predictability

✦ recoverability

✦ relevance

✦ reliability

✦ repeatability

✦ reproducibility

✦ responsiveness

✦ reusability

✦ robustness

✦ safety

✦ scalability

✦ seamlessness

✦ serviceability

✦ securability

✦ simplicity

✦ stability

✦ survivability

✦ sustainability

✦ tailorability

✦ testability

✦ timeliness

✦ understandability

✦ usability

✦ ...

Page 12: Design Patterns: A Lightweight Introduction

SUBJECTIVE ATTRIBUTES?✦ accessibility

✦ accountability

✦ accuracy

✦ adaptability

✦ administrability

✦ affordability

✦ agility

✦ auditability

✦ availability

✦ credibility

✦ standards compliance

✦ process capabilities

✦ compatibility

✦ composability

✦ configurability

✦ correctness

✦ customizability

✦ degradability

✦ demonstrability

✦ dependability

✦ deployability

✦ distributability

✦ durability

✦ evolvability

✦ extensibility

✦ fidelity

✦ flexibility

✦ installability

✦ integrity

✦ interchangeability

✦ interoperability

✦ learnability

✦ maintainability

✦ manageability

✦ mobility

✦ modularity

✦ nomadicity

✦ operability

✦ portability

✦ precision

✦ predictability

✦ recoverability

✦ relevance

✦ reliability

✦ repeatability

✦ reproducibility

✦ responsiveness

✦ reusability

✦ robustness

✦ safety

✦ scalability

✦ seamlessness

✦ serviceability

✦ securability

✦ simplicity

✦ stability

✦ survivability

✦ sustainability

✦ tailorability

✦ testability

✦ timeliness

✦ understandability

✦ usability

✦ ...

Page 13: Design Patterns: A Lightweight Introduction

WHAT DOES GOOD CODE LOOK LIKE?

Page 14: Design Patterns: A Lightweight Introduction

void qs(int l[], int m, int n) { int kk, i, j, k; if (m < n) { k = cp(m,n); s(&l[m], &l[k]); kk = l[m]; i = m + 1; j = n; while(i <= j) { while((i <= n) && (l[i] <= kk)) i++; while((j >= m) && (l[j] > kk)) j--; if (i < j) s(&l[i], &l[j]); } s(&l[m], &l[j]); qs(l, m, j-1); qs(l, j+1, n); }}

OBFUSCATION?

C

Page 15: Design Patterns: A Lightweight Introduction

void qs(int l[], int m, int n) {! int kk, i, j, k;

! if (m < n) {! ! k = cp(m,n);! ! s(&l[m], &l[k]);! ! kk = l[m];! ! i = m + 1; j = n;! ! while(i <= j) {! ! ! while((i <= n) && (l[i] <= kk)) i++;! ! ! while((j >= m) && (l[j] > kk)) j--;! ! ! if (i < j) s(&l[i], &l[j]);! ! }! !! ! s(&l[m], &l[j]);! !! ! qs(l, m, j-1);! ! qs(l, j+1, n);! }}

CODE?C

Page 16: Design Patterns: A Lightweight Introduction

void quicksort(int list[], int m, int n) {! int key, i, j, k;

! if (m < n) {! ! k = choose_pivot(m,n);! ! swap(&list[m], &list[k]);! ! key = list[m];! ! i = m + 1; j = n;! ! while(i <= j) {! ! ! while((i <= n) && (list[i] <= key)) i++;! ! ! while((j >= m) && (list[j] > key)) j--;! ! ! if (i < j) swap(&list[i], &list[j]);! ! }! !! ! swap(&list[m], &list[j]);! !! ! quicksort(list, m, j-1);! ! quicksort(list, j+1, n);! }}

ART?C

Page 17: Design Patterns: A Lightweight Introduction

qs [] = []qs (x:xs) = qs (filter (< x) xs) ++ [x] ++ qs (filter (>= x) xs)

ABSORPTION?

HASKELL

Page 18: Design Patterns: A Lightweight Introduction

class Employee ... int payAmount() { switch(type) { case ENGINEER: return monthlySalary; case SALESMAN: return monthlySalary + 0.1 * totalSales; case MANAGER: return monthlySalary + bonus; default: throw Exception("Incorrect Employee"); } }

CONDITIONALS...

+ payAmount

– monthlySalary– bonus– totalSales– type

Employee

C#

Page 19: Design Patterns: A Lightweight Introduction

abstract class Employee ... abstract int payAmount();

class Engineer: Employee ... int payAmount() {

return monthlySalary;}

class Salesman: Employee ... int payAmount() {

return monthlySalary + 0.1 * totalSales; }

class Manager: Employee ... int payAmount() {

return monthlySalary + bonus; }

... V.S. POLYMORPHISM

+ payAmount– monthlySalaryEmployee

+ payAmountEngineer

+ payAmount– totalSales

Salesman

+ payAmount– bonus

Manager

C#

Page 20: Design Patterns: A Lightweight Introduction

IS GOOD CODE DIFFERENT IN FORM?

Page 21: Design Patterns: A Lightweight Introduction

SOFTWARE DESIGN

Object Oriented Design is more than just drawing diagrams:

• Good OO designers rely on lots of experience

• OO systems exhibit recurring structures that promote:

abstraction flexibility modularity elegance

• Therein lies valuable design knowledge

• This reusable knowledge is captured through patterns

Page 22: Design Patterns: A Lightweight Introduction

ALEXANDER’S PATTERN

P = ⟨ problem, forces, solution ⟩

... a recognized good solution for a recurrent problem, which balances all relevant forces, optimizing the tradeoffs for a specific purpose.

... are prescriptive rather than descriptive. It drives the designer to make a choice based on the forces and the resulting consequences.

Page 23: Design Patterns: A Lightweight Introduction

PATTERNS ARE EVERYWHERE

... in nature ...

Page 24: Design Patterns: A Lightweight Introduction

... in music ...

PATTERNS ARE EVERYWHERE

Page 25: Design Patterns: A Lightweight Introduction

... in architecture ...

PATTERNS ARE EVERYWHERE

Page 26: Design Patterns: A Lightweight Introduction

... in art ...

PATTERNS ARE EVERYWHERE

Page 27: Design Patterns: A Lightweight Introduction

... in mathematics ...

PATTERNS ARE EVERYWHERE

Page 28: Design Patterns: A Lightweight Introduction

Patterns analyze and formalize empirical knowledge in search for stronger invariants, allowing rational design choices and uncovering newer abstractions.

WHY PATTERNS?

Page 29: Design Patterns: A Lightweight Introduction

LIGHT ON TWO SIDES **Once the building's major rooms are in position, we have to fix its actual shape...

When they have a choice, people will always gravitate to those rooms which have light on two sides, and leave the rooms which are lit only from one side unused and empty.

Page 30: Design Patterns: A Lightweight Introduction

Locate each room so that it has outdoor space outside it on at least two sides, and then place windows in these outdoor walls so that natural light falls into every room from more than one direction.

LIGHT ON TWO SIDES **

Page 31: Design Patterns: A Lightweight Introduction

• Gamma et al. Design Patterns: Elements of Reusable Object-Oriented Software.

• It presents 3 categories of 23 interconnected patterns on OO design.

• It’s taught worldwide in CS/SE as an introductory book on software architecture and design:

DESIGN PATTERNS

• Singleton,

• Composite,

• Façade,

• Abstract Factory,

• Proxy,

• State,

• Bridge,

• Factory method,

• Decorator,

• Adapter,

• Flyweight,

• ...

Still:

• They have a context which may need to be adapted.

• They are abstractions, not out of the box components.

Page 32: Design Patterns: A Lightweight Introduction

• Bucshmann et al. series of Pattern Oriented Software Architecture

• Higher-level concerns: architecture v.s. design.

• Decoupled from OO compared to the GoF book (different domain).

• Layers,

• Pipes and Filters,

• Blackboard,

• Broker,

• Model-View-Controller,

• Presentation-Abstraction-Control,

• Microkernel,

• Reflection,

• Whole-part,

• Master-slave,

• Proxy,

• Command Processor,

• View Handler,

• ...

ARCHITECTURAL PATTERNS

Page 33: Design Patterns: A Lightweight Introduction

There are several books and pattern languages that focus on specific domains such as:

• Distributed systems,

• Adaptive systems,

• Requirements engineering,

• Sociology,

• Psychology,

• Documentation,

• Frameworks,

• Interaction design,

• Pedagogical,

• ...

Some are even about patterns themselves:• A Pattern Language for Patern Writing,

• Meta-Patterns.

DOMAIN-SPECIFIC

Page 34: Design Patterns: A Lightweight Introduction

ANATOMY OF A PATTERNName. Usually a “catchy” noun that describes what the pattern “builds.”

Aliases. Also known as...

Sketch. A metaphorical figure.

Context. Describe the setting for the problem. Include a description of the target user.

Forces. Why the problem is not trivial. Discuss other possible solutions and why they won’t work.

Problem. Unbiased by the solution.

Solution. Include enough detail so the user can implement the solution, but don’t

restrict the pattern to a narrow list of specifics.

Resulting Context. Include the new problems that appear as a result of applying the pattern that may require new patterns for their resolution.

Rationale. Explain the rationale behind the solution. Convince the reader. Tell stories! Share your expertise.

Known Uses. Briefly list or describe places where the pattern is used.

Related Patterns. Briefly describe any related patterns and their relationships to this pattern.

Page 35: Design Patterns: A Lightweight Introduction

EXTENDED ANATOMY...Name. Usually a “catchy” noun that describes what the pattern “builds.”

Aliases. Also known as...

Sketch. A metaphorical figure.

Context. Describe the setting for the problem. Include a description of the target user.

Forces. Why the problem is not trivial. Discuss other possible solutions and why they won’t work.

Problem. Unbiased by the solution.

Solution. Include enough detail so the user can implement the solution, but don’t

restrict the pattern to a narrow list of specifics.

Resulting Context. Include the new problems that appear as a result of applying the pattern that may require new patterns for their resolution.

Rationale. Explain the rationale behind the solution. Convince the reader. Tell stories! Share your expertise.

Known Uses. Briefly list or describe places where the pattern is used.

Related Patterns. Briefly describe any related patterns and their relationships to this pattern.

Page 36: Design Patterns: A Lightweight Introduction

EXAMPLE

Page 37: Design Patterns: A Lightweight Introduction

OBSERVER PATTERNAlso known asSubject Observer, Publish-Subscribe, Callback.

IntentDefine a one-to-many dependency between objects so that when one object (called the subject) changes state, all its dependents (called the observers) are notified and updated automatically.

MotivationThe need to maintain consistency between related objects without making classes tightly coupled

Page 38: Design Patterns: A Lightweight Introduction

SKETCH

(doesn’t know the observers)

Page 39: Design Patterns: A Lightweight Introduction

APPLICABILITY

Use the Observer pattern in any of the following situations:

• When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.

• When a change to one object requires changing others

• When an object should be able to notify other objects without making assumptions about those objects

Page 40: Design Patterns: A Lightweight Introduction

STRUCTURE

abstract class abstract class or interface

Page 41: Design Patterns: A Lightweight Introduction

PARTICIPANTSSubject

•Keeps track of its observers

•Provides an interface for attaching and detaching Observer objects

Observer•Defines an interface for update notification

ConcreteSubject•The object being observed

•Stores state of interest to ConcreteObserver objects

•Sends a notification to its observers when its state changes

ConcreteObserver•The observing object

•Stores state that should stay consistent with the subject's

• Implements the Observer update interface to keep its state consistent with the subject's

Page 42: Design Patterns: A Lightweight Introduction

COLLABORATIONS

Page 43: Design Patterns: A Lightweight Introduction

CONSEQUENCES+ Minimal coupling between the Subject and the Observer

• Can reuse subjects without reusing their observers and vice versa

• Observers can be added without modifying the subject

• All subject knows is its list of observers

• Subject does not need to know the concrete class of an observer, just that each observer implements the update interface

• Subject and observer can belong to different abstraction layers

+ Support for event broadcasting

• Subject sends notification to all subscribed observers

• Observers can be added/removed at any time

– Possible cascading of notifications

• Observers are not necessarily aware of each other and must be careful about triggering updates

– Simple update interface requires observers to deduce changed item

Page 44: Design Patterns: A Lightweight Introduction

IMPLEMENTATION• How does the subject keep track of its observers?

• Array, linked list

• What if an observer wants to observe more than one subject?

• Have the subject tell the observer who it is via the update interface

• Who triggers the update?

• The subject whenever its state changes

• The observers after they cause one or more state changes

• Some third party object(s)

• Make sure the subject updates its state before sending out notifications

• How much info about the change should the subject send to the observers?

• Push Model - Lots

• Pull Model - Very Little

Page 45: Design Patterns: A Lightweight Introduction

IMPLEMENTATION

• Can the observers subscribe to specific events of interest?

• If so, it's publish-subscribe

• Can an observer also be a subject?

• Yes!

• What if an observer wants to be notified only after several subjects have changed state?

• Use an intermediary object which acts as a mediator

• Subjects send notifications to the mediator object which performs any necessary processing before notifying the observers

Page 46: Design Patterns: A Lightweight Introduction

KNOWN USES

• Smalltalk Model/View/Controller user interface framework

• Model = Subject

• View = Observer

• Controller is whatever object changes the state of the subject

• Java 1.1 AWT/Swing Event Model

Page 47: Design Patterns: A Lightweight Introduction

RELATED PATTERNS

• Mediator. To encapsulate complex update semantics.

Page 48: Design Patterns: A Lightweight Introduction

JAVA BUILT-IN SUPPORT

interface java.util.Observer

• void update(Observable o, Object arg)

class java.util.Observable (=Subject)

• void addObserver(Observer o)

• void deleteObserver(Observer o)

• void setChanged()

• void notifyObservers(Object arg)

Page 49: Design Patterns: A Lightweight Introduction

A CONCRETE SUBJECT

public class ConcreteSubject extends Observable ... private String name; private float price;

public ConcreteSubject(String name, float price) { this.name = name; this.price = price; }

public String getName() { return name; }

public float getPrice() { return price; }

public void setPrice(float price) { this.price = price; setChanged(); notifyObservers(price); }

JAVA

Page 50: Design Patterns: A Lightweight Introduction

A CONCRETE OBSERVER

public class ConcreteObserver implements Observer ... private float price;

public ConcreteObserver() { price = 0; }

public void update(Observable obj, Object arg) { price = (Float) arg; }

public getPrice() { return price; }

JAVA

Page 51: Design Patterns: A Lightweight Introduction

TEST SCENARIO

@Test public void test1() { ConcreteSubject s = new ConcreteSubject("Corn", 1.29f); ConcreteObserver o = new ConcreteObserver(); s.addObserver(o); s.setPrice(4.57f); assertEquals(4.57f, o.getPrice()); }

JAVA

Page 52: Design Patterns: A Lightweight Introduction

?