Lecture1 Introduction
Lecture1 Introduction
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
Ndejje University 4
REUSABILITY EXAMPLE
INSTEAD
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”
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;
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.
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
Disadvantages:
Interface may not (efficiently) provide all desired
operations.
Indirection may reduce performance
Ndejje University 21
Design pattern example 1 (Subclassing – inheritance)
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.
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
Ndejje University 28
Purpose based Design Patterns Classification
Creational – Concerned with the purpose of object
creation or class instantiation
Ndejje University 29
Scope Based Design Patterns Classification
Class Patterns deals with the relationships amongst
the classes and their subclasses
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.
Ndejje University 32
Design Patterns Classification
Ndejje University 33
Design patterns classification cont’d
Purpose
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:
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:
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.
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
Ndejje University 43
Simple Simulation of Duck behavior
All ducks Quack and Swim the super class DUCK
takes care of the implementation code. But
Ndejje University 44
WHAT IF WE WANT TO SIMULATE FLYING
DUCKS?
Duck
quack()
swim()
display()
fly()
// other duck methods
MallardDuck RedheadDuck
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.
Ndejje University 48
Duck simulation recast using interfaces
Interfaces
Flyable Quackable Duck
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.
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
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
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