SlideShare a Scribd company logo
1 of 44
DESIGN PATTERNS
Introduction
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. 2
RECOMMENDED TEXTBOOKS
 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.
3
MARKS DISTRIBUTION
 6-8 Quizzes: 15%
 2 Assignments: 25%
 Mid term Exam:30%
 Final Exam: 30%
4
OUTLINE
 Introduction to Design Patterns
 Describing Design Patterns
 The Design Patterns Catalog
 How to Select and Use a Design Pattern
 Creational Patterns
 Abstract Factory, Builder, Singleton etc.
 Structural Patterns
 Adapter, Bridge, Composite etc.
 Behavioral Patterns
 Command, Interpreter, Observer, Strategy etc.
5
WHAT’S A GOOD OBJECT ORIENTED
DESIGN
 Design should be SPECIFIC to the problem at
hand
AND
 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
6
REUSABILITY EXAMPLE
 Novelists & Playwrights seldom write from
scratch
INSTEAD
 Follow PATTERNS like ‘Tragically flawed Hero’
(Macbeth, Hamlet) or ‘The Romantic Novel’
7
WHAT IS A 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.
8
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
9
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.
10
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
11
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
12
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
13
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 14
MVC PATTERN CONT’D
A=10%
B=40%
C=30%
D=20%
Application data
A
B
C
D
A DCB
Relative Percentages
Y 10 40 30 20
X 15 35 35 15
Z 10 40 30 20
A B C D
Change notification
Requests, modifications
Model
15
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.
16
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.
17
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
resposibility.
18
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
19
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
20
DESIGN PATTERNS
CLASSIFICATION
Purpose
Creational Structural Behavioral
Scope Class Factory Method Adapter(Class) Interpreter
Template Method
Object Abstract Factory
Builder
Prototype
Singleton
Adapter(Object)
Bridge
Composite
Decorator
Façade
Flyweight
Proxy
Chain of Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
21
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 22
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
23
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.
24
PATTERNS AND FRAMEWORKS
 A software framework is a set of cooperating
classes that make up a reusable design for a
specific class of software [Deu89,JF88]
 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 25
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. 26
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
27
SIMPLE SIMULATION OF DUCK
BEHAVIOR
Duck
quack()
swim()
display()
// other duck methods
MallardDuck
display()
// looks like mallard
RedheadDuck
display()
// looks like redhead
Other duck
types
28
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.
29
WHAT IF WE WANT TO SIMULATE
FLYING DUCKS?
Duck
quack()
swim()
display()
fly()
// other duck methods
MallardDuck
display()
// looks like mallard
RedheadDuck
display()
// looks like redhead
Other duck
types
30
TRADEOFFS IN USE OF
INHERITANCE AND MAINTENANCE
Duck
quack()
swim()
display()
fly()
// other duck methods
MallardDuck
display()
// looks like mallard
RubberDuck
quack()
//overridden to squeak
display()
// looks like rubberduck
fly()
// override to do nothing
RedheadDuck
display()
// looks like redhead
One could override the
fly method to the appropriate
thing – just as the quack
method below.
31
EXAMPLE COMPLICATED: ADD A
WOODEN DECOY DUCKS TO THE
MIX
DecoyDuck
quack(){
// override to do nothing
}
display()
// display decoy duck
fly (){
//override to do nothing
}
Inheritance is not always the right
answer. Every new class that inherits
unwanted behavior needs to be
overridden.
How about using interfaces instead?
32
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
33
DUCK SIMULATION RECAST USING
INTERFACES
Duck
swim()
display()
// other duck methods
MallardDuck
display()
fly()
quack()
Quackable
quack()
Flyable
fly()
RedheadDuck
display()
fly()
quack()
RubberDuck
display()
quack()
DecoyDuck
display()
Interfaces
34
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…
35
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)
36
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
37
38
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. 39
IMPLEMENTING DUCK BEHAVIORS -
REVISITED
FlyWithWings
fly(){
// implements duck
flying
}
<<interface>>
FlyBehavior
fly()
<<interface>>
QuackBehavior
quack()
Quack
quack(){
// implements duck
quacking
}
FlyNoWay
fly(){
// do nothing –
Can’t fly
}
Squeak
quack(){
// implements duck
squeak
}
MuteQuack
quack(){
// do nothing –
Can’t quack
}
Key now is that Duck class will delegate
its flying and quacking behavior instead of
implementing these itself
40
IN THE DUCK SIMULATION
CONTEXT…
41
Duck
FlyBehavior: flyBehavior
QuackBehavior: quackBehavior
performQuack()
swim()
display()
performFly()
//other duck-like methods
Duck
Behaviors
41
DUCK SIMULATION RECAST USING
THE NEW APPROACH
42
MallardDuck
display()
RedHeadDuck
display()
RubberDuck
display()
DecoyDuck
display()
Duck
FlyBehavior: flyBehavior
QuackBehavior: quackBehavior
performQuack()
performFly()
setFlyBehavior()
setQuackBehavior()
swim()
display()
<<interface>>
FlyBehavior
fly()
FlyWithWings
fly()
// implements duck
flying
FlyNoWay
fly()
// do nothing –
Can’t fly
<<interface>>
QuackBehavior
quack()
Quack
quack()
// implements
duck
quacking
Squeak
quack()
// implements
squeak
Mutequack
quack()
// do nothing
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
43
THE STRATEGY PATTERN
44
The Strategy Pattern defines a family of algorithms,
Encapsulates each one, and makes them
interchangeable. Strategy lets the algorithm vary
independently from clients that use it.

More Related Content

What's hot

Design Patterns
Design PatternsDesign Patterns
Design Patternssoms_1
 
Uml diagrams
Uml diagramsUml diagrams
Uml diagramsbarney92
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design patternMindfire Solutions
 
Overview of UML Diagrams
Overview of UML DiagramsOverview of UML Diagrams
Overview of UML DiagramsManish Kumar
 
Design Pattern in Software Engineering
Design Pattern in Software EngineeringDesign Pattern in Software Engineering
Design Pattern in Software EngineeringManish Kumar
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1Shahzad
 
Software architecture design ppt
Software architecture design pptSoftware architecture design ppt
Software architecture design pptfarazimlak
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns pptmkruthika
 

What's hot (20)

Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Design pattern
Design patternDesign pattern
Design pattern
 
Uml diagrams
Uml diagramsUml diagrams
Uml diagrams
 
Unified Modeling Language
Unified Modeling LanguageUnified Modeling Language
Unified Modeling Language
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
 
Uml
UmlUml
Uml
 
Overview of UML Diagrams
Overview of UML DiagramsOverview of UML Diagrams
Overview of UML Diagrams
 
Design Pattern in Software Engineering
Design Pattern in Software EngineeringDesign Pattern in Software Engineering
Design Pattern in Software Engineering
 
UML
UMLUML
UML
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1
 
Design patterns tutorials
Design patterns tutorialsDesign patterns tutorials
Design patterns tutorials
 
Software architecture design ppt
Software architecture design pptSoftware architecture design ppt
Software architecture design ppt
 
Use Case Modeling
Use Case ModelingUse Case Modeling
Use Case Modeling
 
UML Diagrams
UML DiagramsUML Diagrams
UML Diagrams
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
 
Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)
 
Software Architecture
Software ArchitectureSoftware Architecture
Software Architecture
 
Class diagrams
Class diagramsClass diagrams
Class diagrams
 
Types of UML diagrams
Types of UML diagramsTypes of UML diagrams
Types of UML diagrams
 

Viewers also liked

презентация1 1 (1)
презентация1 1 (1)презентация1 1 (1)
презентация1 1 (1)amjad1977a
 
1 de um casarão do outro mundo
1   de um casarão do outro mundo1   de um casarão do outro mundo
1 de um casarão do outro mundoFatoze
 
Carta aos discípulos
Carta aos discípulosCarta aos discípulos
Carta aos discípulosFatoze
 
Holocaust Photo Project Directions
Holocaust Photo Project   DirectionsHolocaust Photo Project   Directions
Holocaust Photo Project DirectionsMs. Geiger
 
PORTAFOLIO DE GESTIÓN DE TALENTO HUMANO
PORTAFOLIO DE GESTIÓN DE TALENTO HUMANO PORTAFOLIO DE GESTIÓN DE TALENTO HUMANO
PORTAFOLIO DE GESTIÓN DE TALENTO HUMANO Lizita Peña
 
Manejo de los alimentos
Manejo de los alimentosManejo de los alimentos
Manejo de los alimentosSandy-66
 
Regressionanalyse
RegressionanalyseRegressionanalyse
RegressionanalysePaul Marx
 

Viewers also liked (9)

презентация1 1 (1)
презентация1 1 (1)презентация1 1 (1)
презентация1 1 (1)
 
1 de um casarão do outro mundo
1   de um casarão do outro mundo1   de um casarão do outro mundo
1 de um casarão do outro mundo
 
Carta aos discípulos
Carta aos discípulosCarta aos discípulos
Carta aos discípulos
 
Holocaust Photo Project Directions
Holocaust Photo Project   DirectionsHolocaust Photo Project   Directions
Holocaust Photo Project Directions
 
Listado de morosos al 4/10/2010
Listado de morosos al 4/10/2010Listado de morosos al 4/10/2010
Listado de morosos al 4/10/2010
 
PORTAFOLIO DE GESTIÓN DE TALENTO HUMANO
PORTAFOLIO DE GESTIÓN DE TALENTO HUMANO PORTAFOLIO DE GESTIÓN DE TALENTO HUMANO
PORTAFOLIO DE GESTIÓN DE TALENTO HUMANO
 
Manejo de los alimentos
Manejo de los alimentosManejo de los alimentos
Manejo de los alimentos
 
Regressionanalyse
RegressionanalyseRegressionanalyse
Regressionanalyse
 
Por que o planejamento é importante?
Por que o planejamento é importante?Por que o planejamento é importante?
Por que o planejamento é importante?
 

Similar to Introduction to design patterns

Cs 1023 lec 9 design pattern (week 2)
Cs 1023 lec 9 design pattern (week 2)Cs 1023 lec 9 design pattern (week 2)
Cs 1023 lec 9 design pattern (week 2)stanbridge
 
Module 2 design patterns-2
Module 2   design patterns-2Module 2   design patterns-2
Module 2 design patterns-2Ankit Dubey
 
PATTERNS01 - An Introduction to Design Patterns
PATTERNS01 - An Introduction to Design PatternsPATTERNS01 - An Introduction to Design Patterns
PATTERNS01 - An Introduction to Design PatternsMichael Heron
 
Unit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxUnit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxDrYogeshDeshmukh1
 
SADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfSADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfB.T.L.I.T
 
Design pattern & categories
Design pattern & categoriesDesign pattern & categories
Design pattern & categoriesHimanshu
 
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...Anil Sharma
 
12266422.ppt
12266422.ppt12266422.ppt
12266422.pptCSEC5
 
Final sdp ppt
Final sdp pptFinal sdp ppt
Final sdp pptnancy_17
 
Cse 6007 fall2012
Cse 6007 fall2012Cse 6007 fall2012
Cse 6007 fall2012rhrashel
 
Software Patterns
Software PatternsSoftware Patterns
Software Patternskim.mens
 
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Luis Valencia
 
Object Oriented Approach for Software Development
Object Oriented Approach for Software DevelopmentObject Oriented Approach for Software Development
Object Oriented Approach for Software DevelopmentRishabh Soni
 
Design and Implementation in Software Engineering
Design and Implementation in Software EngineeringDesign and Implementation in Software Engineering
Design and Implementation in Software EngineeringKourosh Sajjadi
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and DesignDr. C.V. Suresh Babu
 

Similar to Introduction to design patterns (20)

Cs 1023 lec 9 design pattern (week 2)
Cs 1023 lec 9 design pattern (week 2)Cs 1023 lec 9 design pattern (week 2)
Cs 1023 lec 9 design pattern (week 2)
 
Module 2 design patterns-2
Module 2   design patterns-2Module 2   design patterns-2
Module 2 design patterns-2
 
.Net design pattern
.Net design pattern.Net design pattern
.Net design pattern
 
PATTERNS01 - An Introduction to Design Patterns
PATTERNS01 - An Introduction to Design PatternsPATTERNS01 - An Introduction to Design Patterns
PATTERNS01 - An Introduction to Design Patterns
 
Unit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxUnit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptx
 
Unit iii design patterns 9
Unit iii design patterns 9Unit iii design patterns 9
Unit iii design patterns 9
 
SADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfSADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdf
 
Design pattern & categories
Design pattern & categoriesDesign pattern & categories
Design pattern & categories
 
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...
 
12266422.ppt
12266422.ppt12266422.ppt
12266422.ppt
 
Final sdp ppt
Final sdp pptFinal sdp ppt
Final sdp ppt
 
Cse 6007 fall2012
Cse 6007 fall2012Cse 6007 fall2012
Cse 6007 fall2012
 
Software Patterns
Software PatternsSoftware Patterns
Software Patterns
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
 
Object Oriented Approach for Software Development
Object Oriented Approach for Software DevelopmentObject Oriented Approach for Software Development
Object Oriented Approach for Software Development
 
Patterns Overview
Patterns OverviewPatterns Overview
Patterns Overview
 
Design and Implementation in Software Engineering
Design and Implementation in Software EngineeringDesign and Implementation in Software Engineering
Design and Implementation in Software Engineering
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and Design
 

Recently uploaded

Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 

Recently uploaded (20)

Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 

Introduction to design patterns

  • 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. 2
  • 3. RECOMMENDED TEXTBOOKS  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. 3
  • 4. MARKS DISTRIBUTION  6-8 Quizzes: 15%  2 Assignments: 25%  Mid term Exam:30%  Final Exam: 30% 4
  • 5. OUTLINE  Introduction to Design Patterns  Describing Design Patterns  The Design Patterns Catalog  How to Select and Use a Design Pattern  Creational Patterns  Abstract Factory, Builder, Singleton etc.  Structural Patterns  Adapter, Bridge, Composite etc.  Behavioral Patterns  Command, Interpreter, Observer, Strategy etc. 5
  • 6. WHAT’S A GOOD OBJECT ORIENTED DESIGN  Design should be SPECIFIC to the problem at hand AND  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 6
  • 7. REUSABILITY EXAMPLE  Novelists & Playwrights seldom write from scratch INSTEAD  Follow PATTERNS like ‘Tragically flawed Hero’ (Macbeth, Hamlet) or ‘The Romantic Novel’ 7
  • 8. WHAT IS A 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. 8
  • 9. 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 9
  • 10. 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. 10
  • 11. 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 11
  • 12. 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 12
  • 13. 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 13
  • 14. 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 14
  • 15. MVC PATTERN CONT’D A=10% B=40% C=30% D=20% Application data A B C D A DCB Relative Percentages Y 10 40 30 20 X 15 35 35 15 Z 10 40 30 20 A B C D Change notification Requests, modifications Model 15
  • 16. 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. 16
  • 17. 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. 17
  • 18. 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 resposibility. 18
  • 19. 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 19
  • 20. 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 20
  • 21. DESIGN PATTERNS CLASSIFICATION Purpose Creational Structural Behavioral Scope Class Factory Method Adapter(Class) Interpreter Template Method Object Abstract Factory Builder Prototype Singleton Adapter(Object) Bridge Composite Decorator Façade Flyweight Proxy Chain of Responsibility Command Iterator Mediator Memento Observer State Strategy Visitor 21
  • 22. 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 22
  • 23. 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 23
  • 24. 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. 24
  • 25. PATTERNS AND FRAMEWORKS  A software framework is a set of cooperating classes that make up a reusable design for a specific class of software [Deu89,JF88]  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 25
  • 26. 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. 26
  • 27. 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 27
  • 28. SIMPLE SIMULATION OF DUCK BEHAVIOR Duck quack() swim() display() // other duck methods MallardDuck display() // looks like mallard RedheadDuck display() // looks like redhead Other duck types 28
  • 29. 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. 29
  • 30. WHAT IF WE WANT TO SIMULATE FLYING DUCKS? Duck quack() swim() display() fly() // other duck methods MallardDuck display() // looks like mallard RedheadDuck display() // looks like redhead Other duck types 30
  • 31. TRADEOFFS IN USE OF INHERITANCE AND MAINTENANCE Duck quack() swim() display() fly() // other duck methods MallardDuck display() // looks like mallard RubberDuck quack() //overridden to squeak display() // looks like rubberduck fly() // override to do nothing RedheadDuck display() // looks like redhead One could override the fly method to the appropriate thing – just as the quack method below. 31
  • 32. EXAMPLE COMPLICATED: ADD A WOODEN DECOY DUCKS TO THE MIX DecoyDuck quack(){ // override to do nothing } display() // display decoy duck fly (){ //override to do nothing } Inheritance is not always the right answer. Every new class that inherits unwanted behavior needs to be overridden. How about using interfaces instead? 32
  • 33. 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 33
  • 34. DUCK SIMULATION RECAST USING INTERFACES Duck swim() display() // other duck methods MallardDuck display() fly() quack() Quackable quack() Flyable fly() RedheadDuck display() fly() quack() RubberDuck display() quack() DecoyDuck display() Interfaces 34
  • 35. 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… 35
  • 36. 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) 36
  • 37. 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 37
  • 38. 38
  • 39. 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. 39
  • 40. IMPLEMENTING DUCK BEHAVIORS - REVISITED FlyWithWings fly(){ // implements duck flying } <<interface>> FlyBehavior fly() <<interface>> QuackBehavior quack() Quack quack(){ // implements duck quacking } FlyNoWay fly(){ // do nothing – Can’t fly } Squeak quack(){ // implements duck squeak } MuteQuack quack(){ // do nothing – Can’t quack } Key now is that Duck class will delegate its flying and quacking behavior instead of implementing these itself 40
  • 41. IN THE DUCK SIMULATION CONTEXT… 41 Duck FlyBehavior: flyBehavior QuackBehavior: quackBehavior performQuack() swim() display() performFly() //other duck-like methods Duck Behaviors 41
  • 42. DUCK SIMULATION RECAST USING THE NEW APPROACH 42 MallardDuck display() RedHeadDuck display() RubberDuck display() DecoyDuck display() Duck FlyBehavior: flyBehavior QuackBehavior: quackBehavior performQuack() performFly() setFlyBehavior() setQuackBehavior() swim() display() <<interface>> FlyBehavior fly() FlyWithWings fly() // implements duck flying FlyNoWay fly() // do nothing – Can’t fly <<interface>> QuackBehavior quack() Quack quack() // implements duck quacking Squeak quack() // implements squeak Mutequack quack() // do nothing
  • 43. 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 43
  • 44. THE STRATEGY PATTERN 44 The Strategy Pattern defines a family of algorithms, Encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Editor's Notes

  1. ,