SDA - 4 - Chapter Four

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 63

Software Design and Architecture

By: Ashenafi C. and Amsalu T.

AASTU, April 2020


1
Chapter Four

Design Patterns

2
Design Patterns
 Pattern is a solution to a problem in a context.

» Context: the situation in which the pattern apply


» Problem: goal you are trying to achieve in this context (any
constraints that occur in that context)
» Solution: what you are after – general design that anyone
can apply which resolves the goal and set of constraints.

3
Cont’d
 Design Patterns - descriptions of communicating objects and
classes that are customized to solve a general design
problem in a particular context.
» A problem that someone has already solved.
» A model or design to use as a guide.
» More formally: “A proven solution to a common problem in a specified
context."
 Real World Examples:
» Blueprint for a house
» Manufacturing

4
Cont’d
 In software engineering, a design pattern is a general repeatable
solution to a commonly occurring problem in software design.

 A design pattern is a standardized solution to a problem commonly


encountered during object-oriented software development.

 A design pattern is not a finished design that can be


transformed directly into code.
» It is a description or template for how to solve a problem that can
be used in many different situations.
» Design patterns help designers to choose design alternatives that
make a system reusable and avoid alternatives that compromise
reusability.
» Design patterns can even improve the documentation and maintenance
of existing systems by furnishing an explicit specification of class and
5
History of Design Patterns
 Christopher Alexander (Civil Engineer) in 1977 wrote
» “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.”

 In 1995, the principles that Alexander established were


applied to software design and architecture. The result was
the book:
“Design Patterns: Elements of Reusable Object-Oriented Software” by
Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
 Also commonly known as “The Gang of Four”.

6
What is Gang of Four (GoF)?
 In 1995, four authors Erich Gamma, Richard Helm, Ralph
Johnson and John Vlissides published a book titled Design
Patterns - Elements of Reusable Object-Oriented
Software which initiated the concept of Design Pattern in
Software development.
 These authors are collectively known as Gang of Four (GOF).
 According to these authors design patterns are primarily
based on the following principles of object orientated
design.
– Program to an interface not an implementation
– Favor object composition over inheritance

7
The Gang of Four
 Defines a Catalog of different design patterns.
 Three different types
» Creational – “creating objects in a manner suitable for the situation”.
– These design patterns provide a way to create objects while hiding the
creation logic, rather than instantiating objects directly using new operator.
This gives program more flexibility in deciding which objects need to be
created for a given use case.
» Structural – “ease the design by identifying a simple way to realize
relationships between entities”.
– These design patterns concern class and object composition. Concept
of inheritance is used to compose interfaces and define ways to compose
objects to obtain new functionalities.
» Behavioral – “common communication patterns between objects”.
– These design patterns are specifically concerned with communication
between objects.
8
The Gang of Four: Pattern Catalog
Creational Behavioral
Abstract Factory Chain of Responsibility
Builder Command
Factory Method Interpreter
Prototype Iterator
Singleton Mediator
Memento
Structural Observer
Adapter State
Bridge Strategy
Composite Template Method
Decorator Visitor
Façade
Flyweight
Proxy

9
Characteristics of Design Patterns
 Viewpoints – ways to describe patterns.
» Static: class model (building blocks).
» Dynamic: sequence or state diagram (operation).
 Levels – decomposition of patterns.
» Abstract level describes the core of the pattern.
» Concrete (= non abstract) level describes the particulars of this case.
 Roles – the “players” in pattern usage.
» Application of the design pattern itself.
» Clients of the design pattern application.
» Setup code initializes and controls.

10
Cont’d

11
Design Pattern Forms
 Delegation
» An implementation mechanism in which an object forwards
(delegates) a request to another object.
» The delegate carries out the request on behalf of the original
object.

 Recursion
» Part of the pattern essentially uses itself.
– Example
 Constructing graphical user interfaces that allow for windows
within window.

12
Delegation

13
Cont’d

14
Recursion

15
Design Pattern Goals
 To support reuse of successful designs.
 To facilitate software evolution.
» Add new features easily, without breaking existing ones
 In short, we want to design for change.

 Principles to achieve the above goals:


» Reduce implementation dependencies between elements of a
software system
– Program to an interface, not an implementation
– Favor composition over inheritance
– Use delegation

16
Elements of Design Patterns
 In general, a pattern has four basic elements:
» Pattern name- is a handle we can use to describe a design
problem, its solutions, and consequences in a word or two.
» Problem - When to apply the pattern. It explains the problem
and its context.
» Solution - Elements that make up the pattern, their
relationships, responsibilities, and collaborations.
» Consequences - Results and trade-offs of applying the pattern.

17
Basic UML/OMT Notations in the GOF Patterns
Class Diagram Generalization/Specialization

•Abstract classes
appear in slanted type
Object Instantiation

18
Class Association UML/OMT Notations

19
Type of Design Patterns

 Creational patterns : patterns provide instantiation mechanisms,


making it easier to create objects in a way that suits the situation.

 Structural design patterns : generally deal with relationships between


entities, making it easier for these entities to work together.

 Behavioural design patterns : patterns are used in communications


between entities and make it easier and more flexible for these entities to
communicate.
 Scope - what the pattern applies to:
o Class Patterns - Focus on the relationships between classes and their subclasses –
Involve class inheritance reuse.
o Object Patterns - Focus on the relationships between objects - Involve object
composition reuse.

20
1. Creational Patterns
 This design patterns is all about class instantiation.

 Simplicity – some patterns make object creation easier so that clients will
not contain large, complex code to instantiate an object.

 Creational patterns are ones that create objects for you, rather than
having you instantiate objects directly. This gives your program more
flexibility in deciding which objects need to be created for a given case.

21
1.1. Factory Method Patterns
 Creational Design Pattern.

 The factory related patterns are design patterns that allow for
the creation of objects without specifying the type of
object that is to be created in code.

 A factory class contains a method that allows determination


of the created type at run-time.

22
Hotel Example

Hotel Room

+getPrice()

Room rm; Single Double Family


// if roomtype is single
rm = new Single();
// if roomtype is family
+getPrice() +getPrice() +getPrice()
rm = new Family();

23
Duck Example

24
Pizza - Example
 Suppose that you are required to develop a system that
accepts orders for pizza. There are three types of pizza:
cheese, Greek, and pepperoni. The pizzas differ according
to the dough used, the sauce used, and the toppings.

 Draw a class diagram for the system.

25
Pizza - Example

26
Pizza - Example

27
Pizza - Example

28
Encapsulating Object Creation

29
Using a Simple Factory

30
Factory
 Factories handle the detail of object creation

 Once we have a SimplePizzaFactory, our orderPizza()


method just becomes a client of that object

 Any time it needs a pizza it asks the pizza factory to make


one

 The orderPizza() method just cares that it gets a pizza!

31
SimplePizzaFactory

32
New SimplePizzaFactory

Why is this better?

SimplePizzaFactory may
have many clients. By
encapsulating the pizza
creating in one class, we
now only have one place
to make modifications
when the implementation
changes.

33
Simple Factory Pattern
 Intent
o Creates objects without exposing the instantiation logic to
the client
o Referes to the newly created object through a common
interface
 Implementation

34
2. Structural Pattern
 This design patterns is all about Class and Object
composition.
 Structural class-creation patterns use inheritance to
compose interfaces.
 Structural object-patterns define ways to compose objects to
obtain new functionality.

35
Adapter Pattern
 A Structural pattern.

 Convert the interface of a class into another interface that


the client expects. Adapter lets classes work together that
could not otherwise do so, because of incompatible
interfaces.

 (Essentially, we need a way to create a new interface for an


object that does the right stuff but has the wrong interface).

36
Adapter Pattern
 Intent: Match an existing object beyond your control to a
particular interface.
 Problem: A system has the right data and behavior but the
wrong interface.
 Solution: Define an adapter class which acts as an
intermediary. The adapter does little work itself but merely
translates commands from one form to another.
 Implementation: Contain the existing class in another class.
Have the containing class match the required interface and
call the methods of the containing class.

37
Adapter Pattern – When to Use

 The Adapter pattern enables a


system to use classes whose
interfaces don't quite match its
requirements

 Especially useful for off-the-shelf


code, for toolkits, and for
libraries.

38
Adapter Pattern - Example

interface Shape { ​
  void drawRec(int x1, int y1, int x2, int y2); ​
}​

class LegacyRectangle { ​
  public void drawRec(int x, int y, int w, int h) {   ​
    println("rectangle" + x + ',' + y)​
    println("with width " + w + " and height " + h); ​
  } ​
}

39
Adapter Pattern - Example

class RectangleAdapter implements Shape { ​



  private LegacyRectangle adaptee = ​
                      new LegacyRectangle(); ​

  public void drawRec(int x1, int y1, int x2, int y2)
{ ​
   adaptee.drawRec( ​
        x1,y1,Math.abs(x2-x1), Math.abs(y2-y1)); ​
  } ​
}

40
Adapter Pattern - Exercise

 Write
a client that would use the
RectangleAdapter to draw a rectangle.

41
Adapter Pattern - Example
public class ShapeBuilding {
public static void main(String [] args){
RectangleAdapter rectangle=
new RectangleAdapter();
int topx=10, topy=10;
int bottomx=110,bottomy=30;
rectangle.drawRec(topx,topy,
bottomx,bottomy);

}
}

42
Composition vs Inheritance
 Object-Orientated Programming (OOP) has two well known candidates
for the reuse of functionality: inheritance (white box) and composition
(black box).

 If you try to reuse code by inheriting from a class you will make the
subclass dependent on the parent class. This makes the system
unnecessarily complex, less testable and makes the exchange of
functionality at run time unnecessarily hard.

 Composition means that one class uses another. You will further promote
decoupling by defining the interfaces clearly. That will also give the
advantage that implementations can be easily replaced.

43
3. Behavioral Design Pattern
 This design patterns is all about Class's objects communication.
 Behavioral patterns are those patterns that are most specifically
concerned with communication between objects.
» Observer Design Pattern
» Memento Design Pattern

44
Observer Pattern

 Defines a “one-to-many” dependency between objects so


that when one object changes state, all its dependents are
notified and updated automatically

 a.k.a Dependence mechanism / publish-subscribe /


broadcast / change-update

45
Subject & Observer

 Subject
» the object which will frequently change its state and upon which other
objects depend

 Observer
» the object which depends on a subject and updates according to its
subject's state.

46
Observer Pattern - Example

a b c b
Observers
x 6030 10
y 503020 a c
z 8010 10 a b c

a = 50%
Subject b = 30%
c = 20%

requests, modifications
change notification

47
Observer Pattern - Working

A number of Observers “register” to receive notifications of


changes to the Subject. Observers are not aware of the presence
of each other.

When a certain event or “change” in Subject occurs, all


Observers are “notified’.

48
Observer Pattern - Key Players

 Subject
» has a list of observers
» Interfaces for attaching/detaching an observer
 Observer
» An updating interface for objects that gets notified of changes in a
subject.
 ConcreteSubject
» Stores “state of interest” to observers
» Sends notification when state changes
 ConcreteObserver
» Implements updating interface

49
Observer Pattern - UML

observers
Subject Observer
Attach(Observer)
Detach(Observer)
Update()
for all o in
Notify()
observers {
o -> Update()}

ConcreteObserver
observerState =
subject Update() subject->GetState()
ConcreteSubject observerState
SetState()
GetState()
return subjectState
subjectState

50
Observer Pattern - Collaborations

:ConcreteSubject :ConcreteObserver-1 :ConcreteObserver-2

SetState()
Notify()

Update()

GetState()

Update()

GetState()

51
Observer Pattern - Implementation

interface Observer {
void update (Observable sub, Object arg)
// repaint the pi-chart
Java terminology for Subject.
}
class Observable {

public void addObserver(Observer o) {}


public void deleteObserver (Observer o) {}
public void notifyObservers(Object arg) {}
public boolean hasChanged() {}

}
52
Memento Pattern

 Memento pattern is used to restore the state of an


object to a previous state.
 Memento pattern falls under the behavioral pattern
category.

53
Implementation

 Memento pattern uses three actor classes.


» Memento contains state of an object to be restored.
» Originator creates and stores states in Memento objects and
» Caretaker object is responsible to restore object state from Memento.

54
Intent

 Capture and externalize an object’s state without


violating encapsulation.

Restore the object’s state at some later time.


» Useful when implementing checkpoints and undo
mechanisms that let users back out of tentative
operations or recover from errors.
» Entrusts other objects with the information it needs to
revert to a previous state without exposing its internal
structure and representations.

55
Forces

 Application needs to capture states at certain times or at


user discretion. May be used for:
» Undo / redo
» Log errors or events
» Backtracking

 Need to preserve encapsulation


» Don’t share knowledge of state with other objects

 Object owning state may not know when to take state


snapshot.

56
Participants

 Memento
» Stores internal state of the Originator object. Originator decides
how much.
» Protects against access by objects other than the originator.
» Mementos have two interfaces:
– Caretaker sees a narrow interface.
– Originator sees a wide interface.

57
Participants (continued)

 Originator
» Creates a memento containing a snapshot of its current
internal state.
» Uses the memento to restore its internal state.

58
Participants (continued)

 Caretaker
» Is responsible for the memento’s safekeeping.
» Never operates on or examines the contents of a memento.

59
Implementation

 When mementos get created and passed back to their


originator in a predictable sequence, then Memento can
save just incremental changes to originator’s state.

60
Memento Pattern - Structure
• Intent
• Without violating encapsulation, capture and externalize an object's internal
state so that the object can be returned to this state later.
• Structure

61
Memento Pattern – Example

public class Originator {


private int number; private File file = null;
public Originator(){}
public Memento getMemento() { return new Memento(this);}
public void setMemento(Memento m){number = m.number; file = m.file;}
}

private class Memento implements java.io.Serializable{


private int number;
private File file = null;
public Memento( Originator o){ number = o.number; file = o.file;}
}
62
Benefits of Design Patterns
 Capture expertise and make it accessible to non-experts in a
standard form
 Facilitate communication among developers by providing a
common language
 Make it easier to reuse successful designs and avoid
alternatives that diminish reusability
 Facilitate design modifications
 Improve design documentation
 Improve design understandability

63

You might also like