SDA - 4 - Chapter Four
SDA - 4 - Chapter Four
SDA - 4 - Chapter Four
Design Patterns
2
Design Patterns
Pattern is a solution to a problem in a context.
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.
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.
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
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.
22
Hotel Example
Hotel Room
+getPrice()
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.
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
31
SimplePizzaFactory
32
New SimplePizzaFactory
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.
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
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
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
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
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
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 {
53
Implementation
54
Intent
55
Forces
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
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
63