You are on page 1of 60

Mr.

Kateete Twaha
katstwa92@gmail.com
+256 778 313 421

Ndejje University 1
Outline
 Course Description
 Design Patterns
 Gang of Four (GOF)
 Usage of Design Patterns
 Why Design Patterns
 Elements of Design Patterns
 Description of Design Patterns
 MVC Pattern
 The catalog of Design Patterns
 Classification of Design Patterns
 How Design Patterns solve problems
 Selecting Design Patterns
 Patterns and Algorithms
 Patterns and Frameworks

Ndejje University 2
Course Description
Traditionally, OO designers have developed their own
private "catalogs" of solutions to recurring design problems.
More recently, advocates of design patterns have created
public repositories of patterns that more formally
 Identify these recurring design problems
 Document possible solutions to these problems through the
general arrangement and composition of objects and classes
 Discuss the advantages and disadvantages of the various
solutions and
 Provide implementation examples. This course will introduce
the student to the concept of design patterns, examine several
patterns in detail, apply these patterns to specific problems,
and point the student to design pattern resources.

Ndejje University 3
What’s a good object oriented design
Design should be SPECIFIC to the problem at hand

Also be GENERIC enough to address future problems


and requirements
So the design should be REUSABLE
Expert designers REUSE successful designs
Consequently REUSABLE designs are recurring
PATTERNS of classes and objects in OO Systems

Ndejje University 4
REUSABILITY EXAMPLE

Novelists & Playwrights seldom write from scratch

INSTEAD

Follow PATTERNS like ‘Tragically flawed Hero’


(Macbeth, Hamlet) or ‘The Romantic Novel’

Ndejje University 5
Design Patterns
Software Design is a fundamental aspect of the software
development life-cycle.
A design pattern describes a good solution to a recurring
problem in a particular context in software design.
Design patterns represent the best practices used by
experienced object-oriented software developers.
Design patterns are solutions to general problems that
software developers faced during software development.
These solutions were obtained by trial and error by
numerous software developers over quite a substantial
period of time.

Ndejje University 6
Design pattern is;
A standard solution to a common programming
problem
– a design or implementation structure that achieves a
particular purpose particular purpose
– a high-level programming idiom
• A technique for making g code more flexible
– reduce coupling among program components
shorthand for describing program design
– a d ii f i description o f connect ions among program
components
– the shape of a heap snapshot or object model

Ndejje University 7
Design pattern
 “A proven solution to a common problem in a specified context.”
 Example: We can light a candle if light goes out at night
 Christopher Alexander (Civil Engineer) in 1977 wrote
 “A 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”

 The “gang of four” (GoF)


 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.

Ndejje University 8
In summary, Design patterns is,
A standard solution to a common programming problem
A technique for making code more flexible by making it
meet certain criteria
A design or implementation structure that achieves a
particular purpose
A high-level programming idiom
A shorthand for describing certain aspects of program
organization
A connections among program components
The shape of an object diagram or object model

Ndejje University 9
Gang of Four (GOF)
In 1994, 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

Ndejje University 10
Usage of Design Patterns
 Design Patterns have two main usages in software development;

 Common platform for developers: Design patterns provide a


standard terminology and are specific to particular scenario.
 For example, a singleton design pattern signifies use of single object
so all developers familiar with single design pattern will make use of
single object and they can tell each other that program is following a
singleton pattern.

 Best Practices: Design patterns have been evolved over a long period
of time and they provide best solutions to certain problems faced
during software development.
 Learning these patterns helps inexperienced developers to learn
software design in an easy and faster way.

Ndejje University 11
Advantages of Design Patterns
Promote best practices as they capture expert design
knowledge and make it accessible in a standardized
expression format.

Promote communication and streamline


documentation by providing a shorthand for designers.

Support software reuse and increase software quality


and designer/programmer productivity,

Provides a basis or model to improve upon


Ndejje University 12
Why learn Design Patterns
They make it easier to reuse successful designs and
architectures
They can make documentation and maintenance of
the systems easier
Design Patterns help a designer design “right” faster
They provide a vocabulary that can be used amongst
software developers.
Enable us to discuss low-level implementation in a
high-level, abstract manner.
Help in extendibility and avoiding solution redesign

Ndejje University 13
Elements of a Design Pattern
Pattern Name
Is a handle to describe design problem & solution
Problem
Describes when a Pattern is to be applied
Solution
General arrangement of elements to solve a problem
Consequences
Results and Tradeoffs of applying a Pattern
Tradeoffs can be space, time, language etc.

Ndejje University 14
Elements of Design Pattern
The pattern name
 It is a handle we can use to describe a design problem, its solutions, and
consequences in a word or two.
 Naming a pattern immediately increases our design vocabulary.
 It lets us design at a higher level of abstraction.
 Having a vocabulary for patterns lets us talk about them with our colleagues, in
our documentation.
 It makes it easier to think about designs and to communicate them and their
trade-offs to others.
The problem
 Describes when to apply the pattern.
 It explains the problem and its context.
 It might describe specific design problems such as how to represent algorithms
as objects.
 It might describe class or object structures that are symptomatic of an inflexible
design.

Ndejje University 15
Elements of Design Pattern
The solution
 Describes the elements that make up the design, their relationships, responsibilities,
and collaborations.
 The solution doesn't describe a particular concrete design or implementation, because a
pattern is like a template that can be applied in many different situations.
 Instead, the pattern provides an abstract description of a design problem and how a
general arrangement of elements (classes and objects) solves it.
  

The consequences
 are the results and trade-offs of applying the pattern.
 they are critical for evaluating design alternatives and for understanding the costs and
benefits of applying the pattern.
 The consequences for software often concern space and time trade-offs.
 They may address language and implementation issues as well.
 The consequences of a pattern include its impact on a system's flexibility, extensibility,
or portability.
 Listing these consequences explicitly helps you understand and evaluate them.

Ndejje University 16
Describing a Design Pattern
How do we describe design patterns? Graphical notations,
while important and useful, aren't sufficient.
They simply capture the end product of the design process
as relationships between classes and objects. To reuse the
design, we must also record the decisions, alternatives, and
trade-offs that led to it.
Concrete examples are important too, because they help
you see the design in action.
We describe design patterns using a consistent format.
Each pattern is divided into sections according to the
following template. The template lends a uniform structure
to the information, making design patterns easier to learn,
compare, and use.
Ndejje University 17
Describing a Design Pattern
Pattern Name & Classification – Conveys the essence of
the pattern concisely
Intent – What design issue the pattern addresses
Also Known As – Other well known names for this pattern
Motivation – A scenario illustrating a design problem and
how its being solved by the pattern
Applicability – Known situations where the pattern can be
applied
Structure – OMT (Object Modeling ) based graphic
representation of the classes in the pattern
Participants – Classes and objects in the pattern with
their responsibilities

Ndejje University 18
Describing a Design Pattern Cont’d
Collaborations – How the participants collaborate to
carry out their responsibilities
Consequences – What are the results and tradeoffs of
using the pattern
Implementation – Hints on implementation of the
pattern like language dependency
Sample Code – Sample code
Known Uses – Examples
Related Patterns – Other patterns closely related
with the pattern under consideration
Ndejje University 19
Not a Design Pattern
Linked Lists
Hash Tables
Domain Specific designs for entire application or
subsystem
A code solution ready for copy-and-paste
Programming language features
The same every time you see them

Ndejje University 20
Design pattern example 1 (encapsulation – data hiding)
Problem: Exposed fields can be directly manipulated
Violations of the representation invariant
Dependences prevent changing the implementation

Solution: Hide some components


Permit only stylized access to the object

Disadvantages:
Interface may not (efficiently) provide all desired
operations.
Indirection may reduce performance

Ndejje University 21
Design pattern example 1 (Subclassing – inheritance)

Problem: Repetition in implementations


Similar abstractions have similar members (fields,
methods)

Solution: Inherit default members from a superclass


Select an implementation via run-time dispatching

Disadvantages:
Code for a class is spread out, and thus less understandable
Run-time dispatching introduces overhead

Ndejje University 22
MVC Pattern
The main purpose of using MVC pattern is to decouple
the GUI from the Data. It also
gives the ability to provide multiple views for the same
Data.
MVC pattern separates views and models by
establishing a subscribe/notify protocol amongst them
Application of MVC pattern has benefits like
 Classes defining application data and presentation can be
reused.
 Change in one view automatically reflected in other
views. Also, change in the application data is reflected in
all views.
 Defines one-to-many dependency amongst objects so
that when one object changes its state, all its dependents
are notified
Ndejje University 23
MVC Pattern Cont’d
Relative Percentages
A B C D
A
X 15 35 35 15 D
Y 10 40 30 20 B
C
Z 10 40 30 20
A B C D

A=10%
B=40%
C=30% Application data
Change notification
D=20%
Requests, modifications
Model
Ndejje University 24
MVC Pattern Cont’d
 Model: - This section is specially for maintaining data. It is actually where
your business logic, querying database, database connection etc. is actually
implemented.

 Views: - Displaying all or some portion of data, or probably different view of


data. View is responsible for look and feel, Sorting, formatting etc.

 Controller: - They are event handling section which affects either the model
or the view. Controller responds to the mouse or keyboard input to command
Model and View to change. Controllers are associated with views. User
interaction triggers the events to change the Model, which in turn calls some
methods of Model to update its state to notify other registered Views to
refresh their display.

Ndejje University 25
The catalog of Design Patterns
 The catalog contains 23 design patterns. as listed below;
1. Abstract Factory 15. Memento
2. Adapter 16. Observer
3. Bridge 17. Prototype
4. Builder 18. Proxy
5. Chain of Responsibility 19. Singleton
6. Command 20. State
7. Composite 21. Strategy
8. Decorator 22. Template Method
9. Façade 23. Visitor
10. Factory Method
11. Flyweight
12. Interpreter
13. Iterator
14. Mediator

Ndejje University 26
Structure of design patterns catalog

Ndejje University 27
Design Patterns Classification
According to the GOF, the design patterns can be
classified in two ways;
According to the PURPOSE
According to the SCOPE

PURPOSE of Design Patterns reflect what actually


they do.

SCOPE of Design Patterns reflect whether they apply


primarily to Classes or Objects.

Ndejje University 28
Purpose based Design Patterns Classification
Creational – Concerned with the purpose of object
creation or class instantiation

Structural – Deal with composition of classes and


objects

Behavioral – Characterize the ways in which classes


and objects interact and distribute responsibility.

Ndejje University 29
Scope Based Design Patterns Classification
Class Patterns deals with the relationships amongst
the classes and their subclasses

These relationships are established through


INHERITANCE, so they are static, fixed at compile
time.
Object Patterns deals with object relationships which
can be changed at runtime or are dynamic.

Note that most patterns are object patterns.

Ndejje University 30
Purpose & Scope based Design Patterns Classification
Creational Class patterns defer some part of object
creation to subclasses where as creational object patterns
defer it to another object.

Structural class patterns use inheritance to compose


classes, while structural object patterns describe ways to
assemble objects.

Behavioral class patterns use inheritance to describe


algorithms and flow of control, whereas the behavioral
object patterns describe how a group of objects cooperate
to perform a task.
Ndejje University 31
Design Pattern Classification/Types
As per the design pattern reference book Design
Patterns - Elements of Reusable Object-Oriented
Software ,
There are 23 design patterns which can be classified
in three categories:
Creational, Structural and Behavioral patterns.
We'll also discuss another category of design pattern:
J2EE design patterns.

Ndejje University 32
Design Patterns Classification

Ndejje University 33
Design patterns classification cont’d
Purpose

Creational Structural Behavioral

Scope Class Factory Method Adapter(Class) Interpreter


Template Method

Object Abstract Factory Adapter(Object) Chain of Responsibility


Builder Bridge Command
Prototype Composite Iterator
Singleton Decorator Mediator
Façade Memento
Flyweight Observer
Proxy State
Strategy
Visitor

Ndejje University 34
How Design Patterns Solve Design Problems
Finding appropriate objects;
 The hard part about OOD is decomposing a system into
objects
 They help to introduce an abstraction for treating objects
uniformly that doesn’t have a physical counterpart
 They help to identify less obvious abstractions and objects
that can capture them
 These objects are seldom identified in a design earlier and
are discovered while making the design reusable and more
flexible
Determining the object Granularity;
 They help in specifying how to represent complete
subsystems as objects
 They help you in decomposing objects into smaller objects

Ndejje University 35
How Design Patterns Solve Design Problems
Specifying Object Interfaces;
Help you in defining interfaces and the kinds of data
that get sent across them
Might also tell what NOT to put into an interface
Also specify relationships across interfaces
Designing for Change;
Help you to avoid dependence on specific operations
Help you to avoid dependence on hardware and
software platforms
Help to avoid algorithmic dependencies

Ndejje University 36
Selecting a Design Pattern
 With more than 20 design patterns in the catalog to choose from, it might
be hard to find the one that addresses a particular design problem,
especially if the catalog is new and unfamiliar to you.
 Here are several different approaches to finding the design pattern that's
right for your problem:

i. Consider how design patterns solve design problems.


ii. Scan Intent sections.
iii. Study how patterns interrelate.
iv. Study patterns of like purpose.
v. Examine a cause of redesign.
vi. Consider what should be variable in your design.

Ndejje University 37
Using a Design Pattern
 Once you've picked a design pattern, how do you use it? Here's a step-by-step
approach to applying a design pattern effectively:

1. Read the pattern once through for an overview.


2. Go back and study the Structure, Participants, and Collaborations sections.
3. Look at the Sample Code section to see a concrete example of the pattern in code.
4. Choose names for pattern participants that are meaningful in the application
context.
5. Define the classes.
6. Define application-specific names for operations in the pattern.
7. Implement the operations to carry out the responsibilities and collaborations in the
pattern.

These are just guidelines to get you started. Over time you'll develop your own way of
working with design patterns.

Ndejje University 38
Patterns and Algorithms
Algorithms and data structures generally solve more
fine-grained computational problems like sorting and
searching.

Patterns are typically concerned with broader


architectural issues that have larger-scale effects.

Ndejje University 39
Patterns and Frameworks
A software framework is a set of cooperating classes that
make up a reusable design for a specific class of software.
A framework will dictate overall structure, partitioning of
classes and objects, how the classes or objects collaborate.
A framework is usually not a complete application: it
often lacks the necessary application-specific
functionality.
Examples
Framework for building compiler for different languages
and machines.
For building financial modeling applications

Ndejje University 40
Patterns and Frameworks
Design patterns may be employed both in the design and the
documentation of a framework. A single framework typically
encompasses several design patterns. A framework can be
viewed as the implementation of a system of design patterns.
Frameworks and design patterns are distinct: a framework is
executable software, design patterns represent knowledge and
experience about software. Frameworks are of a physical nature,
patterns are of a logical nature: frameworks are the physical
realization of one or more software pattern solutions; patterns
are the instructions for how to implement those solutions.
Major differences:
 Design patterns are more abstract than frameworks.
 Design patterns are smaller architectural elements than
frameworks.
 Design patterns are less specialized than frameworks.

Ndejje University 41
An Example Case
Goals
Learn how to exploit and gain experience of others
Examine the benefits of design pattern
Learn one specific pattern: Strategy pattern

Ndejje University 42
Simple Simulation of Duck behavior
Duck

quack()
swim()
display()
// other duck methods

MallardDuck RedheadDuck

display() display() Other duck


// looks like mallard // looks like redhead types

Ndejje University 43
Simple Simulation of Duck behavior
All ducks Quack and Swim the super class DUCK
takes care of the implementation code. But

Each duck subtype is responsible for implementing


its own Display method as each duck looks different.

In the super class the Display method is abstract.

Ndejje University 44
WHAT IF WE WANT TO SIMULATE FLYING
DUCKS?
Duck

quack()
swim()
display()
fly()
// other duck methods

MallardDuck RedheadDuck

display() display() Other duck


// looks like mallard // looks like redhead types

Ndejje University 45
Tradeoffs in use of inheritance and maintenance

Duck
One could override the
quack() fly method to the appropriate
swim() thing – just as the quack
display()
method below.
fly()
// other duck methods

MallardDuck
RedheadDuck
RubberDuck
display()
// looks like mallard display()
// looks like redhead quack()
//overridden to squeak
display()
// looks like rubberduck
fly()
// override to do nothing

Ndejje University 46
Example complicated: add a wooden
decoy ducks to the mix.

DecoyDuck
Inheritance is not always the right
answer. Every new class that inherits
quack(){ unwanted behavior needs to be
// override to do nothing overridden.
}
display()
How about using interfaces instead?
// display decoy duck
fly (){
//override to do nothing
}

Ndejje University 47
Using Interfaces in Our
Example
We can take Fly() out of the superclasses.

We make an interface iFlyable containing the Fly()


method. That way the ducks supposed to fly can
implement that interface and have a Fly() method.

Same solution can be implemented for Quack(), we


can make interface iQuackable containing the
Quack() method

Ndejje University 48
Duck simulation recast using interfaces
Interfaces
Flyable Quackable Duck

fly() quack() swim()


display()
// other duck methods

MallardDuck RedheadDuck RubberDuck DecoyDuck

display() display() display() display()


fly() fly() quack()
quack() quack()

Ndejje University 49
Pros & Cons
Not all inherited methods make sense for all subclasses –
hence inheritance is not the right answer
But by defining interfaces, every class that needs to support
that interface needs to implement that functionality…
destroys code reuse and creates a maintenance issue.
So if you want to change the behavior defined by interfaces,
every class that implements that behavior may potentially
be impacted
AND
Change is constant in Software Development
Overtime an application must change and grow or it will
die…

Ndejje University 50
Design Principles to the Rescue
Identify the aspects of your application that vary and
separate them from what stays the same.
OR
Take the parts that vary and encapsulate them, so that
later you can alter or extend the parts that vary
without affecting those that don’t.

 Program to an interface, not to an implementation


(Discussed Later)

Ndejje University 51
Change in Duck Classes According to
the Design Principle
As far as we can tell other than the problems with
Fly() and Quack() the Duck Class is fine.
Now to separate “the parts that change from those
which remain the same”, we can create two sets of
classes apart from the Duck Class.
One set can represent the Quacking behaviors e.g. a
class implements quacking, another implements
squeaking etc.
Similar is the case with Flying behaviors

Ndejje University 52
Ndejje University 53
Design Principle
Program to an interface, not to an implementation
We will use interfaces to represent each behavior
Each Implementation of behavior will implement
these interfaces
So the duck classes won’t implement these interfaces
instead the set of classes for behavior would
implement them.
With our new design the duck classes would USE a
behavior represented by an interface. OR
The actual implementation won’t be locked in the
duck classes.
Ndejje University 54
Implementing duck behaviors - revisited
<<interface>> <<interface>>
FlyBehavior QuackBehavior

fly() quack()

Quack MuteQuack

quack(){ quack(){
// implements duck // do nothing –
FlyWithWings FlyNoWay quacking Can’t quack
} }
fly(){ fly(){
// implements duck // do nothing – Squeak
flying Can’t fly
} } quack(){
// implements duck
Key now is that Duck class will delegate its squeak
flying and quacking behavior instead of }
implementing these itself
Ndejje University 55
In the Duck simulation context…
Duck

FlyBehavior: flyBehavior Duck


QuackBehavior: quackBehavior
Behaviors
performQuack()
swim()
display()
performFly()
//other duck-like methods

56

56

Ndejje University
Duck simulation recast using the new approach
<<interface>>
FlyBehavior
Duck
fly()
FlyBehavior: flyBehavior
QuackBehavior: quackBehavior FlyWithWings FlyNoWay
fly() fly()
performQuack() // implements duck // do nothing –
performFly() flying Can’t fly
setFlyBehavior()
<<interface>>
setQuackBehavior()
QuackBehavior
swim()
display() quack()

Quack Squeak
quack() quack()
MallardDuck RedHeadDuck RubberDuck DecoyDuck // implements // implements
duck squeak
display() display() display() display() quacking
Mutequack
quack()
// do nothing

57

Ndejje University
Design Principle
Favor composition over inheritance

HAS-A can be better than IS-A

Composition lets you encapsulate a family of


algorithms into their own set of classes.

Allows changing behavior at run time

Ndejje University 58
Recommended Resources
Recommended Text
Design Patterns: Elements of Reusable Object-Oriented
Software (1995) by Gamma; ISBN 0-201-63361-2
published by Pearson Education
Additional Reading
Head First Design Patterns (2004) by Freeman; ISBN 0-
596-00712-4 published by O'Reilly and Assoc.

Ndejje University 59
Questions

Ndejje University 60

You might also like