Essential Software Design Patterns Guide
Essential Software Design Patterns Guide
Design Patterns
PT
N
1
• Patterns are used as “building blocks” in software
design. Design Patterns
– Help designers to make important design decisions
EL
correctly.
PT
• If you can master a few important patterns:
– You can easily spot them in your next application
N
design problem and use pattern solutions.
2
Christopher Alexander, A Pattern Language, 1977
• Each pattern:
– Describes a problem which occurs over and
over again.
EL
– Describes the core of the solution to that
PT
problem, in such a way that you can use this
solution a million times over, without ever
N
doing it in the same way twice.
3
• How do other engineering fields find and use Patterns in
patterns? Engineering
– Mature engineering disciplines have handbooks
describing successful solutions to known problems
– Automobile designers don't design cars from
EL
scratch.
– Instead, they reuse standard designs with
PT
successful track records.
• Should software engineers make use of patterns?
N
– Developing software from scratch is expensive
– Patterns support reuse of past knowledge mainly
in the form of software architecture and design.
4
• Architectural Patterns: MVC, Layers etc.
Patterns in
• GoF Design Patterns: Singleton, Observer etc
• GUI Design Patterns: Window per task, Disabled irrelevant things,
Software Design
Explorable interface etc
• Database Patterns: decoupling patterns, resource patterns, cache
patterns etc.
EL
• Concurrency Patterns: Double buffering, Lock object, Producer-
consumer,Asynchronous processing etc.
PT
• J2EE Patterns: Data Access Object, Transfer Objects etc.
• GRASP (General Responsibility Assignment Patterns): Low
coupling/high cohesion, Controller, Law of Demeter (don’t talk to
•
N
strangers), Expert, Creator etc.
Anti-patterns (Bad solutions deceptively appear good): God
class,Singletonitis, Basebean etc.
5
• The concept of a "pattern“:
History of Design patterns
– First expressed in Christopher Alexander's work A Pattern
Language in 1977
– A solution to a common design problem in a certain context.
EL
• In 1990:
– Gang of Four or "GoF" (Gamma, Helm, Johnson, Vlissides)
PT
compiled a catalog of design patterns
• Now assimilated into programming languages:
N
– Example: Decorator, Composite, Iterator pattern
Defines an interface that declares methods for sequentially
accessing the objects in a collection.
6
“Gang of four” (GoF) and GRASP Patterns
• Erich Gamma, Richard Helm, Ralph Johnson &
John Vlissides (Addison-Wesley, 1995)
– Design Patterns book catalogs 23 different patterns
EL
• Larman
PT
– GRASP (General Responsibility Assignment
Software Patterns) pattern
N
• Several other types of patterns are also popular.
7
Elements of Design Patterns
• Design patterns usually have 4 essential
elements:
EL
–Pattern name: Designers’ vocabulary
–Problem: intent, context, and when to apply
PT
–Solution: UML model, skeletal code
N
–Consequences: results and tradeoffs
8
• Codify good design Design Patterns Aim To…
– Distill and generalize experience
– Aids novices and experts alike
• Give important design solutions explicit names
EL
– Common vocabulary
PT
• Save design iterations
– Improve documentation
N
– Improve understandability
– Facilitate restructuring/refactoring
9
Types of Patterns
• Architectural patterns
EL
• Design patterns
PT
• Code patterns (Idioms)
N
10
Architectural Patterns
• Architectural designs concern the overall structure
of software systems.
EL
– Architectural designs cannot directly be programmed.
– Form a basis for more detailed design.
PT
• Architectural patterns:
N
– Relevant to providing high-level solutions to large problems.
11
Design Patterns
• A design pattern:
– Suggests classes in a design solution.
– Also, defines the interactions required among the
EL
classes.
• Design pattern solutions are described in terms
PT
of:
N
– Classes, their instances, their roles and
collaborations, skeletal code.
12
Idioms
• Idioms are a low-level patterns:
– Programming language-specific.
EL
– Describe how to implement a solution to
PT
a particular problem using a given
N
programming language.
13
Idioms
• Idioms in English language:
– A group of words that has meaning different from a simple
juxtaposition of the meanings of the individual words.
EL
– Example: “Raining cats and dogs”
PT
• A C idiom:
for(i=0;i<1000;i++){
}
N
14
• A pattern: Patterns versus Idioms
– Describes a recurring problem
– Describes a core solution
– Used for generating many distinct designs
EL
• An Idiom though describes solution to a recurring problem,
PT
is rather restricted:
– Provides only a specific solution, with fewer variations.
N
– Applies only in a narrow context
• e.g., C++ or Java language
15
• If a pattern represents a best practice: Antipattern
– An antipattern represents lessons learned from a
bad design.
• Antipatterns help to recognise deceptive
EL
solutions:
PT
– They appear attractive at first, but turn out to be a
liability later…
N
• Not enough to use patterns in a solution –must
consciously avoid antipatterns.
16
Patterns versus Algorithms
• Are patterns and algorithms identical concepts?
– After all, both target to provide reusable solutions to
problems!
EL
• Algorithms primarily focus on solving problems
PT
with reduced space and/or time requirements:
N
– Patterns focus on understandability and
maintainability of design and easier development.
17
Pros of Design Patterns
• Help capture and disseminate expert knowledge.
– Promotes reuse and helps avoid mistakes.
EL
• Provide a common vocabulary:
– Help improve communication among the
PT
developers.
N
– “The hardest part of programming is coming up
with good variable and function names.”
18
Pros of Design Patterns
• Reduces the number of design
iterations:
EL
– Helps improve the design quality and
PT
designer productivity.
N
19
• Patterns exempify good soutions to common
design problems by making use of:
– Abstraction, Pros of Design Patterns
EL
– Encapsulation
– SRP, OCP, LSP, ISP, DIP
PT
– Separation of concerns
N
– Coupling and cohesion
– Divide and conquer
20
Cons of Design Patterns
• Design patterns do not directly lead to
code reuse.
EL
• To help select the right design pattern at
PT
the right point during a design exercise.
– At present no systematic
N
methodology exists.
21
• Your own designs will improve Why learn Design Patterns?
– borrowing well-tested ideas
– pattern descriptions contain some analysis of tradeoffs
• You will be able to describe complex design ideas to others
EL
– assuming that they also know the same patterns
• You can use patterns to “refactor” existing code
PT
– Improve the structure of existing code without adding new
functionality
N
• You can understand why some aspects of Java language
are that way.
22
Thought for the day…
EL
patterns for procedural
design? ….
PT
N
23
Why No Patterns for Procedural Development?
• Object-Oriented programming languages (and paradigms)
facilitate development of meaningful design patterns.
• Procedural languages need to support:
EL
– Inheritance
PT
– Abstract classes and Interfaces
– Polymorphism N
– Encapsulation
24
Pattern Documentation
• A pattern documented by describing the
situation in which to use the pattern solution.
EL
– Explain the problem and its context.
– Describe situations where it works and does not
PT
work.
N
– Include a list of conditions that must be met
before it makes sense to apply the pattern.
25
Pattern Documentation Artifacts
• Overview of the solution…
• Describe solution in terms of:
– Classes
EL
– Their relationships,
PT
– Responsibilities and
– Collaborations N
• Example code.
26
Design Patterns are NOT…
• NOT designs that can be plugged in and reused as is
– For example, code for linked lists, hash tables
• NOT complex domain-specific designs:
EL
– For an entire application or subsystem.
PT
• Patterns are actually:
– “Descriptions of communicating objects and classes
N
that are customized to solve a general design problem
in a particular context.”
27
GRASP Patterns
EL
PT
N
28
• GRASP: Generalized Responsibility GRASP Patterns
Assignment Software Patterns:
– Larman, “Applying UML and Patterns”
EL
• GRASP patterns can more accurately be
described as best practices:
PT
– If used judiciously, will lead to maintainable,
N
reusable, understandable, and easy to develop
software
29
• GRASP patterns essentially describe how to assign responsibilities
to classes:
– Warning: Some Grasp patterns tend to be vague and need to be
seen as guidelines rather than a concrete solution.
• What is a responsibility? GRASP Patterns
EL
– A contract or obligation of a class
PT
– Responsibilities can include behaviour, data storage, object creation,
etc.
– Usually fall into two categories:
• Doing N
• Knowing
30
• Creator
•
– Who creates an object?
Information Expert
GRASP Patterns
– Which class should be responsible?
• Low Coupling
– Support low dependency and increased reuse
• Controller
EL
– Who handles a system event?
• High Cohesion
– How to keep complexity manageable?
Polymorphism
PT
•
– How to handle behavior that varies by type?
• Pure Fabrication
– How to handle a situation, when you do not want to violate High Cohesion and Low Coupling?
•
•
Indirection
– N
How to avoid direct coupling?
Law of Demeter (Don’t talk to strangers)
– How to avoid knowing about unassociated objects?
31
Expert Pattern
• Problem: Which class should be responsible
for doing a certain thing?
EL
• Solution:
PT
– Assign responsibility to the expert (class that has
all/most information necessary to fulfil the
N
required responsibility).
32
Which class is information expert for computing total
price of a sales transaction?
SaleTrans
EL
date
PT
SaleLineItem Product Specification
description
quantity
N price
Warranty
33
Example 1: Expert
SaleTransaction 1 * SaleLineItem 1 1 ItemSpecification
Class Diagram
EL
PT
1:total
2: subTotal 3: price
:SaleTransaction :SaleLineItem :ItemSpecification
N
Collaboration Diagram: Compute Total Price
34
Sale
Example 1: Class Diagram
date
getTotal
EL
*
SalesLineItem Product
PT
quantity description
price
getSubTotal itemID
N getPrice
35
Example 2:Tic-Tac Toe
Board
Initial domain model
EL
PlayMoveBoundary PlayMoveController Board
PT
Refined domain model
N
•Which class should check game result after a move?
•Which class should play the computer’s move?
36
:playMove :playMove
Boundary Controller
:board Example:
acceptMove checkMoveValidity
Sequence
move
[invalidMove] [invalidMove] Diagram for
announceInvalidMove
announceInvalidMove
checkWinner the play
EL
[game over]
[game over]
announceResult
move use
announceResult
playMove case
PT
checkWinner
[game over] [game over]
announceResult announceResult
N
displayBoardPositions
[game not over]
promptNextMove
getBoardPositions
37
• Expert improves cohesion. Expert Pattern:
An Analysis
– Cohesion: The degree to which the
information and responsibilities of a class are
EL
related to each other
PT
• How cohesion is improved?
N
– The information needed for a responsibility is
in the same class.
38
Creator Pattern: Background
• Every object must be created somewhere.
• Consider making a class responsible for creating an
object if:
EL
– It is an inventory of objects of that type.
– It has the information needed to initialize the object.
PT
– It will be the primary client of the object.
N
• Sometimes this pattern suggests a new class.
• In a Library software, who creates a Member?
39
Creator Pattern
• Problem: Which class should be responsible for
creating a new instance of some class?
• Solution: Assign a class C1 the responsibility to
EL
create class C2 object if
– C1 aggregates objects of type C2
PT
– C1 contains object of type C2
– C1 closely uses C2 N
– C1 has the initializing data for C2
40
Example: Use Case
register Model
Customer customer Clerk
register
EL
sales
Sales Clerk
select
PT
winners
Manager N
Supermarket
Prize scheme
41
Solution: Initial Domain Model
SalesHistory CustomerRegister
EL
1 1
PT
* *
SalesRecords CustomerRecord
N
Initial domain model
42
SalesHistory CustomerRegister
Solution:
1 1
Refined
Domain
* *
Model
SalesRecords CustomerRecord
EL
RegisterCustomerBoundary RegisterCustomerController
PT
RegisterSalesBoundary RegisterSalesController
SelectWinnersBoundary
N SelectWinnersControllers
43
Sequence Diagram
:Customer :Customer
:RegisterCustomer
Boundary
:RegisterCustomer
Controller Register Record
for the Register
register
Customer Use Case
register
checkDuplicate
*match
EL
[duplicate]
showError
PT
generateCIN
<<create>> :Customer
register
Record
displayCIN
N
Sequence Diagram for the register customer use case
44
:Register :Register Sequence Diagram for
:Sales
Sales Sales the Register Sales Use
History
Boundary Controller Case
RegisterSales registerSales
registerSales
EL
<<create>> :Sales
Record
PT
confirm
confirm
N
Sequence Diagram for the register sales use case
45
Refined Sequence
:Register
:Sales Diagram for the
Sales Register Sales Use
History
Boundary Case
registerSales
RegisterSales
EL
<<create>> :Sales
Record
PT
confirm
N
Refined Sequence Diagram for the register sales use case
46
Sequence
:SelectWinner :SelectWinner :Sales :Sales :Customer :Customer
Diagram for the
Boundary Controller History Record Register Record Select Winners
Select
Use Case
SelectWinners
Winners
SelectWinners
*getSales
EL
findWinner
PT
[for each winner]
find WinnerDetails [for each winner]
announces
browse
N
Sequence Diagram for the select winners use case
47
Contraindications (or Caveats) of Creator Pattern
• Object creation may at times involve significant
complexity:
– Recycling instances for performance reasons
EL
– Conditionally creating instances from a family of
PT
similar classes
• In these situations, other patterns are available…
N
– We’ll discuss Factory, abstract factory, object pool, and
other patterns later…
48
Creator: An Analysis
• Whenever one class has the responsibility of
creating instances of another class:
EL
– The two classes get coupled
– Coupling cannot be totally prevented, but we want
PT
to reduce overall coupling.
N
– Whenever two classes are coupled, one class
becomes dependent upon the other.
49
Creator Pattern
• Problem: Which class should be responsible for
creating a new instance of some class?
• Solution: Assign a class C1 the responsibility to
EL
create class C2 object if
– C1 aggregates objects of type C2
PT
– C1 contains object of type C2
– C1 closely uses C2 N
– C1 has the initializing data for C2
50
Creator: Final Analysis
• Creator ensures that coupling due to object
instantiation occurs only between closely
related classes:
EL
– An aggregate or container of a class is already
PT
coupled with that class
– Therefore, assigning the creation responsibility to
N
the container or aggregate does not worsen the
coupling in the design.
51
Controller Pattern
• Problem: Which class should be
responsible for handling the actor
EL
requests?
PT
• Solution: Have a separate controller
N
object for each use case.
52
• Assign the responsibility for receiving and Controller
handling an actor message to a synthesized
controller object
EL
• Do not assign these responsibilities to View
classes (windows, dialogs, etc.) or model classes:
PT
– A user interface object should never be a Controller.
N
– Neither should be an entity class.
53
:playMove :playMove Sequence
Boundary Controller
:board
acceptMove
Diagram for
checkMoveValidity
move
[invalidMove] [invalidMove]
the play
announceInvalidMove
announceInvalidMove
checkWinner
move use
case
EL
[game over]
[game over] announceResult
announceResult
playMove
PT
checkWinner
[game over] [game over]
announceResult announceResult
N
displayBoardPositions
[game not over]
promptNextMove
getBoardPositions
54
• Signs of a bloated controller Bloated Controllers
– A single controller receives many system events
– Controller itself performs tasks instead of delegating them
– Controller has many attributes, maintains a lot of info about the
EL
system or domain
• Better to distribute these to other objects
PT
• Cure: Refactor
N
– Add more controllers
– Delegate responsibility
55
• Problem: How to support low dependency, low change Low
impact, and increased re-use? Coupling
• Why is a class having high coupling bad? Pattern
– Forced to change a class because of changes to related
EL
classes
– Harder to understand a class – cannot do in isolation
PT
– Harder to re-use --- requires presence of classes that it
depends on
N
• Solution: Assign responsibilities so that coupling
remains low.
56
makePayment() 1: create() Two alternative
:Controller p:Payment designs: “Who
creates
2: addPayment(p)
:Sale Payment?”
EL
1: makePayment()
:Controller :Sale
makePayment()
PT
1.1: create()
The second alternative leads to less
coupling
− N
Avoids association between Controller and
Payment
:Payment
57
High Cohesion
• Problems with a class with low cohesion:
– Hard to comprehend
EL
– Hard to reuse
PT
– Hard to maintain
N
– Constantly affected by change
58
Analysis: Controller has Diverse Responsibilities
:Controller :Sale
EL
makePayment() <<create>> p:Payment
PT
addPayment(p)
N
59
Better design: Higher cohesion
:Controller :Sale
EL
addPayment(p)
makePayment() p:Payment
PT
<<create>>
N
60
• High Cohesion An Analysis
–Problem: To keep complexity manageable.
Classes implement a set of cohesive tasks.
–Solution: Assign focused and related
EL
responsibilities to classes.
• Low Coupling
PT
–Problem: To support low dependency and
increased reuse.
N
–Solution: Assign responsibilities so that coupling
remains low.
61
Pure Fabrication – Background
• Suppose a class has responsibilities
unrelated to its main task.
EL
–It is a Bad design --- low cohesion and
PT
high coupling.
N
– How to improve the design?
62
• Problem: Pure Fabrication
– How to improve a design when a class has very high
coupling and low cohesion?
• Solution:
EL
– Assign a highly cohesive set of responsibilities to
an artificial class
PT
– May not represent anything in the problem
domain...
N
– Created only to support high cohesion, low
coupling, and reuse...
63
Low Cohesion Class
Pure Fabrication
Pure Fabrication
EL
High Cohesion Class Invented Class
PT
Fabrication step: Assign a highly
N
cohesive set of responsibilities to
an artificial class.
Takes care of a
similar set of functions
64
Problem: Indirection Pattern
• How to avoid direct coupling between classes?
• How to decouple objects so that low coupling is achieved
EL
and changes become easy?
PT
Solution:
N
• Depend on an interface class,
– So that objects are not directly coupled.
65
Client Server
EL
– Server can change and requires changes to the client.
PT
Client <<Interface>> Indirection
Server
Pattern
Compliant
N
Server1 Server2
66
Example: Naïve Solution Emp
Roster *
Employee
+int EmpType
EL
if (emps[i].empType == FACULTY)
printfFaculty((Faculty)emps[i]);
What if we
else if (emps[i].empType ==STAFF)
PT
need to add
printStaff((Staff)emps[i]); Engineer??
else if (emps[i].empType == SECRETARY)
}
N
printSecretary((Secretary)emps[i]);
67
Emp Indirection
Roster *
<<Interface>> Pattern
Employee
+printInfo() Solution
EL
Faculty Staff Secretary Engineer
+printInfo() +printInfo() +printInfo +printInfo()
PT
for (int i; i<[Link](); i++) {
emps[i].printInfo();
}
}
N
When Engineer is added, printEmpRoster() does not even need to recompile.
PrintEmpRoster() is open to extension, closed for modification.
68
Indirection Advantages
• Low coupling
EL
• Promotes reusability
PT
N
69
Problem: Law of Demeter
• How to avoid a class from interacting with
indirectly associated objects?
EL
1
Bill * Item ItemSpec
Solution: computeTotal getItemSpec findPrice
PT
• If two classes have no other reason to be
directly aware of each other:
N
– Then the two classes should not directly interact.
70
Collaborators
EL
PT
N
71
Law of Demeter
• In a method, calls should only be made to the
methods of following objects:
EL
– This object (or self)
PT
– An object parameter of the method
– An object attribute of self
N
– An object created within the method
72
A Hypothetical example
class A { class B {
private B b = new B(); C c;
EL
}
public void m() {
class C {
PT
[Link](); // High
public void foo() {
coupling: bad
} N }
}
}
73
Law of Demeter: Example
Bill 1 Item ItemSpec
computeTotal * getItemSpec findPrice
EL
Violation: [Link]().findprice()
PT
Bill 1 Item ItemSpec
computeTotal * N
computeSubtotal findPrice
74
• In a class PaperBoy,
LoD Programming Style
– do not use [Link]().getCash(due);
– rather use [Link](due); and in
[Link] (due), use [Link](due)
EL
• Benefit:
– Easier analysis
PT
• Tradeoff:
N
– More statements, but simpler statements
• Experiments show significantly improved maintainability.
75
Law of Demeter: Final Analysis
• Reduces coupling between classes
EL
• Adds a small amount of overhead in
the form of indirect method calls
PT
N
76
“The basic effect of applying this Law is the
creation of loosely coupled classes, whose
implementation secrets are encapsulated. Such
EL
classes are fairly unencumbered, meaning that
to understand the working of one class, you
PT
need not understand the details of many other
N
classes.” Grady Booch
77
• Problem: Polymorphism
– How to handle alternative operations based on
subtypes?
• Solution:
EL
– When alternate behaviours are selected based
on the type of an object,
PT
– Use polymorphic method call to select the
behaviour, N
– Rather than using if statement to test the type.
78
Polymorphism Pattern Advantage
EL
PT
N
79