18CS731
18CS731
DESIGN PATTERNS
SUB CODE: 18CS731
Prepared by:
Dr. Nanda Ashwin, Professor, Dept ISE
DESIGN PATTERNS
TEXT BOOKS:
1. Design Pattern by Erich Gamma, Pearson Education
2. Pattern‘s in JAVA Vol-I BY Mark Grand, Wiley DreamTech
3. Pattern‘s in JAVAVol-II BY Mark Grand, Wiley DreamTech
4. JAVAEnterprise Design Patterns Vol-III Mark Grand, Wiley
Dream Tech
5. Head First Design Patterns By Eric Freeman-Oreilly-spd..
6.Design Patterns Explained By Alan Shalloway,Pearson
Education
UNIT-I 2
S. N O. TO PIC. PPT Slides
UNIT-I 3
L1
Design Patterns
UNIT-I 4
L1
UNIT-I 5
L1
UNIT-I 6
L1
UNIT-I 7
L1
UNIT-I 8
L1
UNIT-I 9
L2
UNIT-I 10
L2
UNIT-I 11
L2
UNIT-I 12
L2
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
UNIT-I 13
L3
UNIT-I 14
L3
UNIT-I 15
L3
UNIT-I 18
L4
UNIT-I 19
L4
UNIT-I 20
L4
UNIT-I 21
L4
UNIT-I 22
L4
UNIT-I 23
L4
UNIT-I 24
The Catalog of Design Pattern
• Memento: Without violating encapsulation,
capture and externalize an object‘s internal
state so that object can be restored to this
state later.
UNIT-I 25
L4
UNIT-I 26
The Catalog of Design Pattern
UNIT-I 27
L4
UNIT-I 28
L5
Organizing the Catalog
•Two criteria
Purpose: what a pattern does
Creational: The process of object creation
Structural: The composition of classes or objects
Behavioral: Characterize the ways in which
classes or objects interact and distribute
responsibility
UNIT-I 30
L6
• FindingAppropriate Objects
– Decomposing a system into objects is the hard part
– Object Oriented Designs often end up with classes with no
counterparts in real world (low-level classes like arrays)
– Strict modeling of the real world leads to a system that
reflects today‘s realities but not necessarily tomorrows
– Design patterns identify less-obvious abstractions
UNIT-I 31
L6
UNIT-I 32
L6
Design Pattern relationship
• Mapping
Memento
Proxy
saving state
Adapter
of iteration
Builder
Iterator Bridge
Enumerating
children
composed Command
Composite
using
adding
respnsibilities sharing
Decorator
to objects composites
changing skin
defining Chain of
versus guts Flyweight
grammar Responsibility
Visitor
sharing Interpreter
Strategy
strategies
Mediator Observer
State
defining
Prototype algorithm´s
steps Template Method Factory Method
UNIT-I 33
L6
UNIT-I 35
L6
UNIT-I 36
L6
UNIT-I 37
L6
UNIT-I 38
L6
• Benefits:
1. Clients remain unaware of the specific types of objects they
use.
2. Clients remain unaware of the classes that implement the
objects.
Clients only know about abstract class(es) defining the
interfaces
• Do not declare variables to be instances of particular
concrete classes
• Use creational patterns to create actual objects.
UNIT-I 39
L6
• White-box reuse:
– Reuse by sub classing (class inheritance)
– Internals of parent classes are often visible to subclasses
– works statically, compile-time approach
– Inheritance breaks encapsulation
• Black-box reuse:
– Reuse by object composition
– Requires objects to have well-defined interfaces
– No internal details of objects are visible
UNIT-I 40
L6
UNIT-I 41
L6
UNIT-I 42
L6
UNIT-I 43
L6
• Object composition
– dynamic at run time
– composition requires objects to respect each
o t h e r s ‘ interfaces
• but does not break encapsulation
– any object can be replaced at run time
– Favoring object composition over class
inheritance helps you keep each class
encapsulated and focused on one task
UNIT-I 44
L6
UNIT-I 45
L6
Delegation
• Two objects are involved in handling a
request: a receiving object delegates
operations to its delegate
Window Rectangle
rectangle
Area() Area()
width
height
UNIT-I 46
L6
Delegation (cont.)
• Makes it easy to compose behaviors at run-time and
to change the way they‘re composed
• Disadvantage:dynamic, highly parameterized
software is harder to understand than more static
software
• Delegation is a good design choice only when it
simplifies more than it complicates
• Delegation is an extreme example of object
composition
UNIT-I 47
L6
UNIT-I 48
L6
UNIT-I 49
L6
UNIT-I 50
L6
UNIT-I 51
L6
UNIT-I 52
L6
• Tight coupling
• Extending functionality by subclassing
• Inability to alter classes conveniently
UNIT-I 54
L6
UNIT-I 55
L6
UNIT-I 56
L6
UNIT-I 57
L6
UNIT-I 58
L6
UNIT-I 59
L7
UNIT-I 60
L7
UNIT-I
62
L8
UNIT-I 63
L8
UNIT-I 64
L9
Online resources
• Pattern FAQ
• http://g.oswego.edu/dl/pd-FAQ/pd-FAQ.html
• Basic patterns
• http://exciton.cs.oberlin.edu/javaresources/DesignPa
tterns/default.htm
• Patterns home page
• http://hillside.net/patterns/
UNIT-I 65
Unit -II
A Case Study: Designing a Document Editor
66
S. N O. TO PIC PPT Slides
1 Document structure L1 4 – 13
2 Formatting L2 14 – 20
3 Embellishment L3 21 – 25
4 Multiple look & feels L4 26 – 30
5 Multiple window systems L5 31 – 35
6 User operations L6 36 – 46
7 Spelling checking & hyphenation L7 47 – 60
8 Concluding Remarks L8 61 – 61
9 Pattern References L8 62 – 67
UNIT-I 67
L1
Design Problems:
• seven problems in Lexis's design:
Document Structure:
The choice of internal representation for the document affects nearly every aspect
of Lexis's design. All editing , formatting, displaying, and textual analysis will
require traversing the representation.
Formatting:
How does Lexi actually arrange text and graphics into lines and columns?
What objects are responsible for carrying out different formatting policies?
How do these policies interact with the document‘s internal representation?
UNIT-II 68
Supporting multiple look-and-feel standards:
Lexi should adapt easily to different look-and-feel standards such as Motif and Presentation
Manager (PM) without major modification.
User Operations:
User control Lexi through various interfaces, including buttons and pull-down menus. The
functionality beyond these interfaces is scattered throughout the objects in the application.
UNIT-I 69
L1
7 Design Problems
1. Document structure
2. Formatting
3. Embellishment
4. Multiple look & feels
5. Multiple window systems
6. User operations
7. Spelling checking &
hyphenation
UNIT-II 69
L1
Document Structure
Goals:
– present document‘s visual aspects
– drawing, hit detection, alignment
– support physical structure
(e.g., lines, columns)
Constraints/forces:
– treat text & graphics uniformly
– no distinction between one & many
UNIT-II 70
L1
Document Structure
• The internal representation for a document
• The internal representation should support
– maintaining the document‘s physical structure
– generating and presenting the document visually
– mapping positions on the display to elements in the
internal representations
UNIT-II 71
L1
UNIT-II 72
L1
UNIT-II 73
L1
UNIT-II 74
L1
UNIT-II 76
L1
UNIT-II 76
L2
Formatting
• A structure that corresponds to a properly
formatted document
• Representation and formatting are distinct
– the ability to capture the document‘s physical structure
doesn‘t tell us how to arrive at a particular structure
• here, we‘ll restrict ―formatting‖ to mean breaking
a collection of glyphs in to lines
UNIT-II 77
L2
Formatting (cont.)
• Encapsulating the formatting algorithm
– keep formatting algorithms completely
independent of the document structure
– make it is easy to change the formatting
algorithm
– We‘ll define a separate class hierarchy for
objects that encapsulate formatting algorithms
UNIT-II 78
L2
Formatting (cont.)
• Compositor and Composition
– We‘ll define a Compositor class for objects that can
encapsulate a formatting algorithm
– The glyphs Compositor formats are the children of a
special Glyph subclass called Composition
– When the composition needs formatting, it calls its
compositor‘s Compose operation
– Each Compositor subclass can implement a different line
breaking algorithm
UNIT-II 79
L2
UNIT-II 80
L2
Formatting (cont.)
• Compositor and Composition (cont.)
– The Compositor-Composition class split ensures a
strong separation between code that supports the
document‘s physical structure and the code for different
formatting algorithms
• Strategy pattern
– intent: encapsulating an algorithm in an object
– Compositors are strategies. A composition is the
context for a compositor strategy
UNIT-II 81
L2
UNIT-II 82
L2
UNIT-II 83
L3
UNIT-II 84
L3
UNIT-II 85
L3
UNIT-II 87
L3
UNIT-II 88
L4
UNIT-II 89
L4
UNIT-II 90
L4
UNIT-II 91
L4
UNIT-II 92
L4
UNIT-II 93
Supporting Multiple Window L5
Systems
UNIT-II 94
Supporting Multiple Window L5
Systems (cont.)
UNIT-II 95
UNIT-I 96
UNIT-I 97
L5
UNIT-II 98
L6
User Operations
• Requirements
– Lexi provides different user interfaces for the
operations it supported
– These operations are implemented in many different
classes
– Lexi supports undo and redo
• The challenge is to come up with a simple and
extensible mechanism that satisfies all of these
needs
UNIT-II 99
L6
UNIT-II 100
L6
UNIT-II 101
L6
UNIT-II 102
UNIT-I 104
L6
past commands
present
UNIT-II 105
L6
present present
UNIT-II 106
L6
present present
UNIT-II 107
L6
present present
UNIT-II 108
L6
UNIT-II 109
L7
Goals:
– analyze text for spelling errors
– introduce potential hyphenation sites
Constraints/forces:
– support multiple algorithms
– don‘t tightly couple algorithms with document
structure
UNIT-II 110
L7
Spelling Checking & Hyphenation (cont‘d)
Solution: Encapsulate Traversal
Iterator
– encapsulates a
traversal algorithm
without exposing
representation details
to callers
– uses Glyph‘s child
enumeration
operation
– This is an example of
a ―preorder iterator‖
UNIT-II 111
L7
Structure
UNIT-II 112
L7
Visitor
• defines action(s) at each step of traversal
• avoids wiring action(s) into Glyphs
• iterator calls glyph‘s accept(Visitor) at each node
• accept() calls back on visitor (a form of ―static
polymorphism‖ based on method overloading by type)
class Visitor {
public:
virtual void visit (Character &);
virtual void visit (Rectangle &);
virtual void visit (Row &);
// etc. for all relevant Glyph subclasses
};
UNIT-II 115
Spelling Checking & Hyphenation (cont‘d) L7
SpellingCheckerVisitor
• gets character code from each character glyph
Can define getCharCode() operation just on Character()
class
• checks words accumulated from character glyphs
• combine with PreorderIterator
class SpellCheckerVisitor : public Visitor {
public:
virtual void visit (Character &);
virtual void visit (Rectangle &);
virtual void visit (Row &);
// etc. for all relevant Glyph subclasses
Private:
std::string accumulator_;
};
UNIT-II 116
L7
Spelling Checking & Hyphenation (cont‘d)
Accumulating Words
Spelling check
performed when a
nonalphabetic character
it reached
UNIT-II 117
Spelling Checking & Hyphenation (cont‘d) L7
Interaction Diagram
• The iterator controls the order in which accept() is called on each glyph in
the composition
• accept() then ―visits‖ the glyph to perform the desired action
• The Visitor can be sub-classed to implement various desired actions
UNIT-II 118
L7
Spelling Checking & Hyphenation (cont‘d)
HyphenationVisitor
• gets character code from each character glyph
• examines words accumulated from character glyphs
• at potential hyphenation point, inserts a...
UNIT-II 120
L7
Spelling Checking & Hyphenation (cont‘d)
VISITOR object behavioral
Intent
centralize operations on an object structure so that they can vary
independently but still behave polymorphically
Applicability
– when classes define many unrelated operations
– class relationships of objects in the structure rarely change, but the
operations on them change often
– algorithms keep state that‘s updated during traversal
Structure
UNIT-II 121
Spelling Checking & Hyphenation (cont‘d) L7
SpellCheckerVisitor spell_check_visitor;
HyphenationVisitor hyphenation_visitor;
Consequences
+ flexibility: visitor & object structure are independent
+ localized functionality
– circular dependency between Visitor & Element interfaces
– Visitor brittle to new ConcreteElement classes
Implementation
– double dispatch
– general interface to elements of object structure
Known Uses
– ProgramNodeEnumerator in Smalltalk-80 compiler
– IRIS Inventor scene rendering
– TAO IDL compiler to handle different backends
124
L8
Part III: Wrap-Up
Concluding Remarks
• design reuse
• uniform design vocabulary
• understanding, restructuring, & team
communication
• provides the basis for automation
• a― new‖ way to think about design
UNIT-II 124
Pattern References L8
Books
Timeless Way of Building, Alexander, ISBN 0-19-502402-8
A Pattern Language, Alexander, 0-19-501-919-9
Design Patterns, Gamma, et al., 0-201-63361-2 CD version 0-201-63498-8
Pattern-Oriented Software Architecture, Vol. 1, Buschmann, et al.,
0-471-95869-7
Pattern-Oriented Software Architecture, Vol. 2, Schmidt, et al.,
0-471-60695-2
Pattern-Oriented Software Architecture, Vol. 3, Jain & Kircher,
0-470-84525-2
Pattern-Oriented Software Architecture, Vol. 4, Buschmann, et al.,
0-470-05902-8
UNIT-II 125
L8
Pattern References (cont‘d)
More Books
Analysis Patterns, Fowler; 0-201-89542-0
Concurrent Programming in Java, 2nd ed., Lea, 0-201-31009-0
Pattern Languages of Program Design
Vol. 1, Coplien, et al., eds., ISBN 0-201-60734-4
Vol. 2, Vlissides, et al., eds., 0-201-89527-7
Vol. 3, Martin, et al., eds., 0-201-31011-2
Vol. 4, Harrison, et al., eds., 0-201-43304-4
Vol. 5, Manolescu, et al., eds., 0-321-32194-4
AntiPatterns, Brown, et al., 0-471-19713-0
Applying UML & Patterns, 2nd ed., Larman, 0-13-092569-1
Pattern Hatching, Vlissides, 0-201-43293-5
The Pattern Almanac 2000, Rising, 0-201-61567-3
UNIT-II 126
L8
UNIT-II 127
L8
Articles
Java Report, Java Pro, JOOP, Dr. Dobb‘s Journal,
Java Developers Journal, C++ Report
UNIT-II 128
L8
UNIT-II 129
L8
Mailing Lists
[email protected]: present & refine patterns
[email protected]: general discussion
[email protected]: discussion on Design Patterns
[email protected]: discussion on
Pattern-Oriented Software Architecture
[email protected]: discussion on user interface patterns
[email protected]: discussion on patterns for business processes
[email protected]: discussion on patterns for distributed systems
UNIT-II 130
unit-2 part-2 PPT Slides
S.NO. TO PIC
1 Creational Pattern Part-I Introduction L1 4–8
2 Abstract Factory L2 9 – 28
3 Builder L3 29 – 39
4 Factory Method L4 40 – 47
5 Prototype L5 48 – 54
6 Singleton L6 55 – 66
UNIT-III 131
Creational Patterns L1
UNIT-III 132
L1
Creational Patterns
• Abstract the instantiation process
– Make a system independent of how objects are created, composed,
and represented
• Important if systems evolve to depend more on object
composition than on class inheritance
– Emphasis shifts from hardcoding fixed sets of behaviors towards a
smaller set of composable fundamental behaviors
• Encapsulate knowledge about concrete classes a system
uses
• Hide how instances of classes are created and put together
UNIT-III 133
L1
UNIT-III 134
L1
UNIT-III 136
L2
UNIT-III 137
L2
Abstract Factory
UNIT-III 138
L2
ABSTRACT FACTORY
(Object Creational)
• Intent:
– Provide an interface for creating families of
related or dependent objects without specifying
their concrete classes
UNIT-III 139
L2
Motivation
• Motivation:
•User interface toolkit supports multiple look-
and-feel standards
(Motif, Presentation Manager)
•Different appearances and behaviors for UI
widgets
•Apps should not hard-code its widgets
UNIT-III 140
L2
ABSTRACT FACTORY
Motivation
Widget Factory Client
CreateScrollBar()
CreateWindow()
Windows
PMWindow MotifWindow
MotifWidgetFactory PMWidgetFactory
CreateScrollBar() CreateScrollBar()
CreateWindow() ScrollBar
CreateWindow()
PMScrollBar MotifScrollBar
UNIT-III 141
L2
Solution:
• Solution:
•Abstract Widget Factory class
•Interfaces for creating each basic kind of
widget
•Abstract class for each kind of widgets,
•Concrete classes implement specific look-
and-feel.
UNIT-III 142
Abstract Factory Structure L2
client
AbstractProductA
AbstractFactory
Operations:
CreateProdA( )
CreateProcB( )
ConcreteProductA1 ConcreteProductA2
ConcreteFactory1 ConcreteFactory2
Operations: Operations:
CreateProdA( ) CreateProdA( )
CreateProcB( ) CreateProcB( )
AbstractProductB
ConcreteProductB1 ConcreteProductB2
UNIT-III
14
L2
Applicability
Use the Abstract Factory pattern when
– A system should be independent of how its products
are created, composed, and represented
– A system should be configured with one of multiple
families of produces
– A family of related product objects is designed to be
used together, and you need to enforce this constraint
– You want to provide a class library of products, and
you want to reveal just their interfaces, not their
implementations
UNIT-III 144
L2
ABSTRACT FACTORY
Participants
• AbtractFactory
– Declares interface for operations that create
abstract product objects
• ConcreteFactory
– Implements operations to create concrete product
objects
• AbstractProduct
– Declares an interface for a type of product object
UNIT-III 145
L2
• ABSTRACT FACTORY
Participants(cont..)
• Concrete Product:
•Defines a product object to be created by concrete
factory
•Implements the abstract product interface
• Client:
•Uses only interfaces declared by Abstract Factory
and AbstractProduct classes
UNIT-III 146
L2
Collaborators
• Usually only one ConcreteFactory instance is used fo
an activation, matched to a specific application
context. It builds a specific product family for client
use -- the client doesn‘t care which family is used -- i
simply needs the services appropriate for the current
context.
UNIT-III 147
L2
Presentation Remark
UNIT-III 148
L2
Consequences
• The Abstract Factory Pattern has the following
benefits:
Consequences
UNIT-III 151
L2
Consequences
Implementation
UNIT-III 155
L2
Know Uses
• Interviews
– used to generate ― look and feel‖ for specific user
interface objects
– uses the Kit suffix to denote AbstractFactory classes,
e.g., WidgetKit and DialogKit.
• also includes a layoutKit that generates different
composite objects depending on the needs of the
current context
ET++
– another windowing library that uses the
AbstractFactory to achieve portability across different
window systems (X Windows and SunView).
UNIT-III 156
L2
Related Patterns
UNIT-III 156
L2
Code Examples
• Skeleton Example
– Abstract Factory Structure
– Skeleton Code
UNIT-III 157
BUILDER L3
(Object Creational)
• Intent:
Separate the construction of a complex object from
its representation so that the same construction
process can create different representations
• Motivation:
– RTF reader should be able to convert RTF to many
text format
– Adding new conversions without modifying the
reader should be easy
UNIT-III 158
L3
• Solution:
•Configure RTFReader class with a Text
Converter object
•Subclasses of Text Converter specialize in
different conversions and formats
•TextWidgetConverter will produce a
complex UI object and lets the user see and
edit the text
UNIT-III 159
L2
Implementation
• Concrete factories are often implemented as
singletons.
Implementation
UNIT-III 162
L2
Know Uses
• Interviews
– used to generate ― look and feel‖ for specific user
interface objects
– uses the Kit suffix to denote AbstractFactory classes,
e.g., WidgetKit and DialogKit.
• also includes a layoutKit that generates different
composite objects depending on the needs of the
current context
ET++
– another windowing library that uses the
AbstractFactory to achieve portability across different
window systems (X Windows and SunView).
UNIT-III 163
L2
Related Patterns
UNIT-III 163
L2
Code Examples
• Skeleton Example
– Abstract Factory Structure
– Skeleton Code
UNIT-III 164
BUILDER L3
(Object Creational)
• Intent:
Separate the construction of a complex object from
its representation so that the same construction
process can create different representations
• Motivation:
– RTF reader should be able to convert RTF to many
text format
– Adding new conversions without modifying the
reader should be easy
UNIT-III 165
L3
• Solution:
•Configure RTFReader class with a Text
Converter object
•Subclasses of Text Converter specialize in
different conversions and formats
•TextWidgetConverter will produce a
complex UI object and lets the user see and
edit the text
UNIT-III 166
L3
UNIT-III 167
L3
UNIT-III 168
L3
Discussion
• Uses Of Builder
– Parsing Program(RTF converter)
– GUI
UNIT-III 169
FACTORY METHOD L4
(Class Creational)
• Intent:
– Define an interface for creating an object, but let
subclasses decide which class to instantiate.
– Factory Method lets a class defer instantiation to
subclasses.
• Motivation:
– Framework use abstract classes to define and maintain
relationships between objects
– Framework has to create objects as well - must instantiate
classes but only knows about abstract classes - which it
cannot instantiate
UNIT-III 170
L4
Motivation:
• Motivation: Factory method encapsulates
knowledge of which subclass to create -
moves this knowledge out of the framework
• Also Known As: Virtual Constructor
UNIT-III 171
L4
FACTORY METHOD
Motivation
docs
Document Application
Open()
CreateDocument() Document* doc=CreateDocument();
Close()
NewDocument() docs.Add(doc);
Save() doc->Open();
OpenDocument()
Revert()
MyApplication
MyDocument
return new MyDocument
CreateDocument()
UNIT-III 172
L4
Applicability
FACTORY METHOD
Structure
Creator
Product
FactoryMethod() ...
product = FactoryMethod()
AnOperation() ...
ConcreteCreator
ConcreteProduct
return new ConcreteProduct
FactoryMethod()
UNIT-III 174
Participants L4
• Product
– Defines the interface of objects the factory method
creates
• ConcreteProduct
– Implements the product interface
• Creator
– Declares the factory method which returns object of type
product
– May contain a default implementation of the factory
method
– Creator relies on its subclasses to define the factory
method so that it returns an instance of the appropriate
UNIT-III 176
Concrete Product.
L4
Factory Method
• Defer object instantiation to subclasses
• Eliminates binding of application-specific subclasses
• Connects parallel class hierarchies
• A related pattern is AbstractFactory
Product Creator
operation() Product createProduct()
ConcreteProduct ConcreteCreator
operation() Product createProduct()
Interactor
0..1
Figure Manipulator
createManipulator() attach(Figure)
PROTOTYPE
(Object Creational)
• Intent:
– Specify the kinds of objects to create using a
prototypical instance, and create new objects by
copying this prototype.
• Motivation:
– Framework implements Graphic class for
graphical components and GraphicTool class for
tools manipulating/creating those components
UNIT-III 178
L5
Motivation
– Actual graphical components are application-
specific
– How to parameterize instances of Graphic Tool
class with type of objects to create?
– Solution: create new objects in Graphic Tool by
cloning a prototype object instance
UNIT-III 179
L5
PROTOTYPE
Motivation
Tool Graphic
Manipulate() Draw(Position)
Clone()
prototype
Staff MusicalNote
WholeNote HalfNote
p = prototype ->Clone()
Draw(Position) Draw(Position)
while(user drags mouse){
Clone() Clone()
p ->Draw(new position)
}
Insert p into drawing Return copy of self Return copy of self
UNIT-III 180
L5
Applicability
UNIT-III 181
L5
Applicability
UNIT-III 182
L5
PROTOTYPE
Structure
client prototype
Prototype
Operation() Clone()
p = prototype ->Clone()
ConcretePrototype1 ConcretePrototype2
Clone() Clone()
UNIT-III 183
L5
Participants:
• Prototype (Graphic)
– Declares an interface for cloning itself
• ConcretePrototype (Staff, WholeNote, HalfNote)
– Implements an interface for cloning itself
• Client (GraphicTool)
– Creates a new object by asking a prototype to clone itself
Collaborations:
• A client asks a prototype to clone Itself.
UNIT-III 184
L5
Motivation
– Actual graphical components are application-
specific
– How to parameterize instances of Graphic Tool
class with type of objects to create?
– Solution: create new objects in Graphic Tool by
cloning a prototype object instance
UNIT-III 185
L5
PROTOTYPE
Motivation
Tool Graphic
Manipulate() Draw(Position)
Clone()
prototype
Staff MusicalNote
WholeNote HalfNote
p = prototype ->Clone()
Draw(Position) Draw(Position)
while(user drags mouse){
Clone() Clone()
p ->Draw(new position)
}
Insert p into drawing Return copy of self Return copy of self
UNIT-III 186
L5
Applicability
UNIT-III 187
L5
Applicability
UNIT-III 188
L5
PROTOTYPE
Structure
client prototype
Prototype
Operation() Clone()
p = prototype ->Clone()
ConcretePrototype1 ConcretePrototype2
Clone() Clone()
UNIT-III 189
L5
Participants:
• Prototype (Graphic)
– Declares an interface for cloning itself
• Concrete Prototype (Staff, Whole Note, Half Note)
– Implements an interface for cloning itself
• Client (GraphicTool)
– Creates a new object by asking a prototype to clone itself
Collaborations:
• A client asks a prototype to clone Itself.
UNIT-III 190
L6
SINGELTON
• Intent:
– Ensure a class only has one instance, and provide
a global point of access to it.
• Motivation:
– Some classes should have exactly one instance
(one print spooler, one file system, one window
manager)
– A global variable makes an object accessible but
doesn‘t prohibit instantiation of multiple objects
– Class should be responsible for keeping track of
its sole interface
UNIT-III 191
L6
Applicability
UNIT-III 192
L6
SINGLETON
Structure
Singleton
Static uniquelnstance
singletonData
UNIT-III 193
L6
UNIT-III 194
L6
Singleton
• Ensures a class has only one instance
UNIT-III 195
L6
Singleton - Benefits
• Controls access to a scarce or unique resource
Singleton – Example 1
• An Application class, where instantiating it makes
a connection to the base operating system and sets
up the rest of the toolkit‘s framework for the user
interface.
• In the Qt toolkit:
QApplication* app = new QApplication(argc, argv)
UNIT-III 198
L6
Singleton – Example 2
• A status bar is required for the application, and
various application pieces need to be able to
update the text to display information to the user.
However, there is only one status bar, and the
interface to it should be limited. It could be
implemented as a Singleton object, allowing only
one instance and a focal point for updates. This
would allow updates to be queued, and prevent
messages from being overwritten too quickly for
the user to read them.
UNIT-III 199
L6
public:
static Singleton* Instance();
protected:
// Creation hidden inside Instance().
Singleton();
private:
Static Singleton* _instance
UNIT-III 200
L6
if (_instance ==0) {
_instance=new Singleton;
}
Return _instance;
// Clients access the singleton
}
// exclusively via the Instance member
// function.
UNIT-III 201
L6
Implementation Points
• Generally, a single instance is held by the
object, and controlled by a single interface.
UNIT-III 202
UNIT-III
UNIT-I 203
Structural Pattern part-I introduction
S. No TOPIC PPT Slides
1 Adaptor L1 3 – 18
2 Bridge L2 19 – 31
3 Composite L3 32 – 37
6 Code Examples L6 43 – 44
7 Reference L7 45 – 45
UNIT-IV 204
Agenda
• Intent & Motivation
• Structure
• Applicability
• Consequences
• Known Uses
• Related Patterns
• References
UNIT-IV 205
L1
What is Adapter?
• Intent:
Change the interface of a class
into another interface which is
expected by the client.
• Also Know As:
Wrapper
UNIT-IV 206
L1
Motivation
1 1
UNIT-IV 207
L1
Structure (Class)
UNIT-IV 208
L1
Structure (Object)
UNIT-IV 209
L1
Applicability
• Use an existing class whose interface does
not match the requirement
• Create a reusable class though the
interfaces are not necessary compatible
with callers
Want to use several existing subclasses,
but it is impractical to subclass
everyone. (Object Adapter Only)
UNIT-IV 210
L1
UNIT-IV 211
L1
UNIT-IV 212
L1
Pluggable Adapters
Pluggable Adapters
Two-way Adapters
} roundPegOperation();
}
UNIT-IV } 216
L1
UNIT-IV 216
L1
Related Patterns
• Adapter can be similar to the remote form
of Proxy. However, Proxy doesn't change
interfaces.
• Decorator enhances another object
without changing its interface.
• Bridge similar structure to Adapter, but
different intent. Separates interface from
implementation.
UNIT-IV 217
L1
Conclusions
• Allows collaboration between classes with
incompatible interfaces
• Implemented in either class-based
(inheritance) or object-based (composition &
delegation) manner
• Useful pattern which promotes reuse and
allows integration of diverse software
components
UNIT-IV 218
L1
Adapter
• You have
– legacy code
– current client
• Adapter changes interface of legacy code so client
can use it
• Adapter fills the gap b/w two interfaces
• No changes needed for either
– legacy code, or
– client
UNIT-IV 219
L1
Adapter (cont.)
class NewTime
{
public:
int GetTime() {
return m_oldtime.get_time() * 1000 + 8;
}
private:
OldTime m_oldtime;
};
UNIT-IV 220
L2
UNIT-IV 221
L2
Overview
Intent
Also Known As
Motivation
Participants
• Structure
• Applicability
• Benefits
• Drawbacks
• Related Pattern I
UNIT-IV 222
L2
UNIT-IV 223
L2
Motivation
Entry
oracleDBEntry FilesysEntry
UNIT-IV 224
L2
Motivation
Entry
Appointment Task
UNIT-IV 225
L2
Motivation
Entry PersistentImp.
getText() initialize()
setText() store()
Destroy() load()
Bridge Destroy()
Participants
UNIT-IV 227
L2
Participants (continue)
UNIT-IV 228
L2
Structure
Client
Abstraction Implementer
OperationImp()
UNIT-IV 229
L2
Applicability
Want to
UNIT-IV 230
L2
Applicability (continue)
UNIT-IV 231
L2
Benefits
Avoid permanent binding between an
abstraction and its implementation
Drawbacks
PersistentImp
PersistentImp
UNIT-IV 233
L2
Composite Pattern
• Intent :
Compose objects into tree structures to
represent part-whole hierarchies. Composite
lets clients treat individual objects and
compositions of objects uniformly.
UNIT-IV 234
L2
Consequences
• decoupling interface & implementation
- implementation of abstraction - can be configured at
run- time
- eliminate compile time dependencies on implementation
- encourages layering
• improved extensibility
- Abstraction & Implementer - can be extended independently
• hiding implementation details from clients
UNIT-IV 235
L3
Composite Pattern
Facilitates the composition of objects into
tree structures that represent part-whole
hierarchies.
These hierarchies consist of both primitive
and composite objects.
UNIT-IV 236
L3
UNIT-IV 237
L3
Observations
• The Component (Graphic) is an abstract class that
declares the interface for the objects in the pattern.
As the interface, it declares methods (such as
Draw) that are specific to the graphical objects.
• Line, Rectangle, and Text are so-called Leafs,
which are subclasses that implement Draw to draw
lines, rectangles, and text, respectively.
UNIT-IV 238
L3
Observations (Continued)
• The Picture class represents a number of
graphics objects. It can call Draw on its
children and also uses children to compose
pictures using primitive objects.
UNIT-IV 239
L3
Concluding Considerations
• The Composite Pattern is used to represent part-
whole object hierarchies.
• Clients interact with objects through the
component class.
• It enables clients to to ignore the specifics of
which leaf or composite class they use.
• Can be used recursively, so that Display can show
both flares and stars.
• New components can easily be added to a design.
UNIT-IV 240
L4
UNIT-IV 241
L4
Motivation
Entry
oracleDBEntry FilesysEntry
UNIT-IV 242
L4
Motivation
Entry
Appointment Task
UNIT-IV 243
L5
Two-way Adapters
} roundPegOperation();
}
UNIT-IV } 245
L5
UNIT-IV 245
L6
Motivation
Entry PersistentImp.
getText() initialize()
setText() store()
Destroy() load()
Bridge Destroy()
Participants
UNIT-IV 247
L7
References
• Becker, Dan. Design networked applications in RMI using the Adapter design pattern.
JavaWorld Magazine, May 1999. http://www.javaworld.com/javaworld/jw-05-1999/jw-
05-networked.html
•
Buschmann et al. A System of Patterns: Pattern-Oriented Software Architecture. John
Wiley and Sons. Chichester. 1996
• Gamma et al. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-
Wesley. Boston. 1995
•
Nguyen, D.X. Tutorial 10: Stacks and Queues: The Adapter Pattern. Rice University.
1999. http://www.owlnet.rice.edu/~comp212/99-fall/tutorials/10/tutorial10.html
•
Whitney, Roger. CS 635 Advanced Object-Oriented Design & Programming. San Diego
State University. 2001.
http://www.eli.sdsu.edu/courses/spring01/cs635/notes/proxy/proxy.html#Heading10
•
Shalloway, Alan., and Trott, James R., Design Patterns Explained: A New Perspective on
Object-Oriented Design, Addison-Wesley, 2002.
•
Rising, Linda., The Patterns Handbook: Techniques, Strategies, and Applications,
Cambridge university Press, 1998.
UNIT-IV 248
Unit-3 part-2
Structural Design Patterns-2
Objectives
S. No Topic PPT Slides
1. Decorator L1 3 – 20
2. Façade L2 21 – 27
3. Proxy L3 28 – 40
4. Flyweight L4 41 – 47
Pattern: Decorator
objects that wrap around other objects to add
useful features
L1
Decorator pattern
• decorator: an object that modifies behavior of, or adds
features to, another object
– decorator must maintain the common interface of the object it
wraps up
• used so that we can add features to an existing simple object
without needing to disrupt the interface that client code
expects when using the simple object
• examples in Java:
– multilayered input streams adding useful I/O methods
– adding designs, scroll bars and borders to GUI controls
L1
Decorator example: I/O
• normal InputStream class has only public int read() method
to read one letter at a time
• decorators such as BufferedReader or Scanner add
additional functionality to read the stream more easily
An example: Decorator
Intent:
Allow to attach responsibilities to objects, extend
their functionality, dynamically
Motivation:
Consider a WYSIWYG editor
The basic textWindow needs various decorations:
borders, tool bars, scroll bars, …
L1
Disadvantages:
• Sub-classing is static – compile-time
• # of sub-classes = # of combinations –
exponential
L1
Implementation:
• Each decorator has a (private) reference to a
Component object (CC or D)
D3 D2 D1 CC
<<Interface>>
Component
Decorator ConcreteComponent
Various decorators
L1
Consequences :
• Decoration can be done dynamically, at run-
time
• When it makes sense, a decoration can be
added several times
• The # of decorators is smaller than the # of
sub-classes in original solution;
avoids lots of feature-heavy classes in the
inheritance hierarchy
L1
Issues to remember :
• A decorator and the Component object it
Program to interfaces,
not to concrete classes
L1
Façade (2)
• Example: graph interface to a simulation engine
SchematicEditor
Graph
Director
2
0..*
Relation Port Entity
Encapsulating Subsystems
Name: Facade design pattern
Problem description:
Reduce coupling between a set of related classes and the rest of
the system.
Solution:
A single Facade class implements a high-level interface for a
subsystem by invoking the methods of the lower-level classes.
Example. A Compiler is composed of several classes:
LexicalAnalyzer, Parser, CodeGenerator, etc. A caller, invokes
only the Compiler (Facade) class, which invokes the contained
classes.
L2
Facade:
Class Diagram
Facade
Facade
service()
Facade: Motivation
Facade: Applicability
• To provide simple interface to a complex
package, which is useful for most clients.
Facade: Consequences
• It shields clients from package components,
thereby reducing the number of objects that
clients deal with and making the package
easier to use.
Proxy
• You want to
– delay expensive computations,
– use memory only when needed, or
– check access before loading an object into memory
• Proxy
– has same interface as Real object
– stores subset of attributes
– does lazy evaluation
L3
Proxy Design Pattern
• Design Purpose
Proxy:
Consequences
Consequences:
Adds a level of indirection between Client and RealObject.
The Client is shielded from any optimization for creating
RealObjects.
L3
Pattern Hatching
Proxy Pattern
Subject
request()
… realSubject->request();
RealSubject Proxy
realSubject
request() request()
… …
L3
Pattern Hatching
Proxy Pattern
We need to find a common structure for the
proxy pattern with our composite pattern
As we recognize, our common interface that we
still want to use for the file-system is Node
And because the Composite structure uses a
common interface already, we can combine the
Proxy ―Subject‖ Interface into our Node
Interface
L3
Pattern Hatching
Node
Proxy getName()
streamIn(istream) Composite Pattern
streamOut(ostream)
Pattern getChild(int)
adopt(Node)
orphan(Node)
children
subject
Flyweight: Consequences
• Space savings increase as more flyweights are
shared.
L5
An example: Decorator
Intent:
Allow to attach responsibilities to objects, extend
their functionality, dynamically
Motivation:
Consider a WYSIWYG editor
The basic textWindow needs various decorations:
borders, tool bars, scroll bars, …
UNIT-V 296
L5
Disadvantages:
• Sub-classing is static – compile-time
• # of sub-classes = # of combinations –
exponential
UNIT-V 297
L5
UNIT-V 298
L5
UNIT-V 299
L5
Implementation:
• Each decorator has a (private) reference to a
Component object (CC or D)
UNIT-V 300
L6
UNIT-V 301
L6
Façade (2)
• Example: graph interface to a simulation engine
SchematicEditor
Graph
Director
2
0..*
Relation Port Entity
Encapsulating Subsystems
Name: Facade design pattern
Problem description:
Reduce coupling between a set of related classes and the rest of
the system.
Solution:
A single Facade class implements a high-level interface for a
subsystem by invoking the methods of the lower-level classes.
Example. A Compiler is composed of several classes:
LexicalAnalyzer, Parser, CodeGenerator, etc. A caller, invokes
only the Compiler (Facade) class, which invokes the contained
classes.
UNIT-V 303
L6
Facade:
Class Diagram
Facade
Facade
service()
UNIT-V 304
L6
Facade:
Consequences
Consequences:
Shields a client from the low-level classes of a subsystem.
Simplifies the use of a subsystem by providing higher-level
methods.
Enables lower-level classes to be restructured without
changes to clients.
Note. The repeated use of Facade patterns yields a layered
system.
UNIT-V 305
L7
2 Command L2 4–9
3 interpreter L3 10 – 12
4 Iterator L4 13 – 17
7 Review Unit-VI L7 25 – 25
UNIT-VI 308
L1
Chain of Responsibility
• Decouple sender of a request from receiver
• Give more than one object a chance to handle
• Flexibility in assigning responsibility
• Often applied with Composite
successor
Client Handler
ContextInterface() handleRequest()
ConcreteHandler1 ConcreteHandler2
handleRequest() handleRequest()
UNIT-VI 309
L1
If interactor != null
interactor.handle(event,this)
else
parent.handleEvent(event)
CompositeFigure parent
UNIT-VI 310
Command: L2
Class Diagram
invokes
Invoker Command
execute()
ConcreteCommand1
<<binds>>
execute()
Receiver
ConcreteCommand2
execute()
UNIT-VI 312
Command: L2
Game1Move
<<binds>> play()
replay()
GameBoard
Game1Move
play()
replay()
UNIT-VI 313
Command: L2
Consequences
Consequences:
The object of the command (Receiver) and the algorithm of
the command (ConcreteCommand) are decoupled.
Invoker is shielded from specific commands.
ConcreteCommands are objects. They can be created and
stored.
New ConcreteCommands can be added without changing
existing code.
UNIT-VI 314
L2
Command
• You have commands that need to be
– executed,
– undone, or
– queued
• Command design pattern separates
– Receiver from Invoker from Commands
• All commands derive from Command and
implement do(), undo(), and redo()
UNIT-VI 315
L2
Command Design Pattern
UNIT-VI 316
L3
Pattern: Interpreter
• Intent: Given a language, interpret sentences
• Participants: Expressions, Context, Client
• Implementation: A class for each expression type
An Interpret method on each class
A class and object to store the global state (context)
• No support for the parsing process
(Assumes strings have been parsed into exp trees)
UNIT-VI 317
L3
UNIT-VI 318
L3
Method Combination
• Build a method from components in different classes
• Primary methods: the ―normal‖ methods; choose the
most specific one
• Before/After methods: guaranteed to run;
No possibility of forgetting to call super
Can be used to implement Active Value pattern
• Around methods: wrap around everything;
Used to add tracing information, etc.
• Is added complexity worth it?
Common Lisp: Yes; Most languages: No
UNIT-VI 319
L4
Iterator pattern
• iterator: an object that provides a standard way to
examine all elements of any collection
• uniform interface for traversing many different data
structures without exposing their implementations
• supports concurrent iteration and element removal
• removes need to know about internal structure of
collection or different methods differentcollections
UNIT-VI 320
L4
Pattern: Iterator
objects that traverse collections
UNIT-VI 321
L4
Iterator interfaces in Java
public interface java.util.Iterator {
public boolean hasNext();
public Object next();
public void remove();
}
} UNIT-VI 322
L4
Iterators in Java
• all Java collections have a method iterator that returns an
iterator for the elements of the collection
• can be used to look through the elements of any kind of
collection (an alternative to for loop)
set.iterator()
List list = new ArrayList(); map.keySet().iterator()
... add some elements ...
map.values().iterator()
} UNIT-VI 323
L4
Adding your own Iterators
• when implementing your own collections, it can be
very convenient to use Iterators
– discouraged (has nonstandard interface):
public class PlayerList {
public int getNumPlayers() { ... }
public boolean empty() { ... }
public Player getPlayer(int n) { ... }
}
– preferred:
public class PlayerList {
public Iterator iterator() { ... }
public int size() { ... }
public boolean isEmpty() { ... }
}
UNIT-VI 324
Command: L5
Class Diagram
invokes
Invoker Command
execute()
ConcreteCommand1
<<binds>>
execute()
Receiver
ConcreteCommand2
execute()
UNIT-VI 326
Command: L5
Game1Move
<<binds>> play()
replay()
GameBoard
Game1Move
play()
replay()
UNIT-VI 327
Command: L5
Consequences
Consequences:
The object of the command (Receiver) and the algorithm of
the command (ConcreteCommand) are decoupled.
Invoker is shielded from specific commands.
ConcreteCommands are objects. They can be created and
stored.
New ConcreteCommands can be added without changing
existing code.
UNIT-VI 328
L6
Pattern: Interpreter
• Intent: Given a language, interpret sentences
• Participants: Expressions, Context, Client
• Implementation: A class for each expression type
An Interpret method on each class
A class and object to store the global state (context)
• No support for the parsing process
(Assumes strings have been parsed into exp trees)
UNIT-VI 329
L6
UNIT-VI 330
L6
Method Combination
• Build a method from components in different classes
• Primary methods: the ―normal‖ methods; choose the
most specific one
• Before/After methods: guaranteed to run;
No possibility of forgetting to call super
Can be used to implement Active Value pattern
• Around methods: wrap around everything;
Used to add tracing information, etc.
• Is added complexity worth it?
Common Lisp: Yes; Most languages: No
UNIT-VI 331
L7
References
• Information about Design Patterns:
– http://msdn.microsoft.com/library/en-
us/dnpag/html/intpatt.asp
– http://www.patternshare.org/
– http://msdn.microsoft.com/architecture/
– http://msdn.microsoft.com/practices/
– http://www.dofactory.com/Patterns/Patterns.aspx
– http://hillside.net/
• Contact: [email protected]
• Slides & code: http://www.daveandal.net/download/
• Article: http://www.daveandal.net/articles/
UNIT-VI 332
Unit-4 part-2
behavioural patterns part-2
S. No TOPIC PPT Slides
2 Mediator L2 5 – 12
3 Memento L3 13 – 32
4
Observer L4 33 – 54
UNIT-VII 334
L1
UNIT-VII 335
L1
Behavioral Patterns (2)
•Iterator: Provide a way to access the elements of anaggregate
object sequentially without exposing itsunderlying
representation.
•Mediator: Define an object that encapsulates how a setof
objects interact. Mediator promotes loose coupling bykeeping
objects from referring to each other explicitly,and lets you vary
their interaction independently.
•Memento: Without violating encapsulation, capture
andexternalize an object‘s internal state so that the object
can be restored to this state later.
•Observer: Define a one-to-many dependency betweenobjects
so that when one object changes state, all itsdependents are
notified and updated automatically.
UNIT-VII 336
Behavioral Patterns (3) L1
•State: Allow an object to alter its behavior when its
internal state changes. The object will appear to change
its class.
•Strategy: Define a family of algorithms, encapsulate
each one, and make them interchangeable. Strategy
lets the algorithm vary independently from clients that
use it.
•Template Method: Define the skeleton of an algorithm
in an operation, deferring some steps to subclasses.
Template Method lets subclasseses redefine certain
steps of an algorithm without changing the algorithm‘s
structure.
•Visitor: Represent an operation to be performed on the
elements of an object structure. Visitor lets you define a
new operation without changing the classes of the
elements on which it operates.
UNIT-VII 337
L2
UNIT-VII 338
L2
Using a Mediator
Unmediated
Collaboration
collaboratorB
1: op1() 2.1: op2()
2: op2()
collaboratorA collaboratorC
Mediated
collaboratorB
Collaboration
1.1: op1()
1.5: op2()
1: op() 1.2: op2()
collaboratorA mediator collaboratorC
1.3: op3()
1.4: op4()
collaboratorD
UNIT-VII 339
L2
Mediator Collaborator
ColleagueA
ColleagueB
ColleagueC
UNIT-VII 340
L2
Mediator as a Broker
Collaborator
«supplier»
ColleagueC
UNIT-VII 341
L2
Mediator Behavior
sd requestService()
consult()
consult()
notify()
consult()
UNIT-VII 342
L2
UNIT-VII 343
L2
Mediators, Façades, and Control
Styles
• The Façade and Mediator patterns
provide means to make control more
centralized.
• The Façade and Mediator patterns
should be used to move from a
dispersed to a delegated style, but
not from a delegated to a centralized
style.
UNIT-VII 344
L2
Summary
Memento Pattern
UNIT-VII 346
L3
References
• doFactory.com
– http://www.dofactory.com/Patterns/PatternMemento.as
px
• Marc Clifton‘s Blog
– http://www.marcclifton.com/tabid/99/Default.aspx
• Software Architecture, ETH, Zurich Switzerland
– http://se.ethz.ch/teaching/ss2005/0050/slides/60_softarc
h_patterns_6up.pdf
UNIT-VII 347
L3
Intent
• Capture and externalize an object‘s state
without violating encapsulation.
• Restore the object‘s state at some later time.
– Useful when implementing checkpoints and
undo mechanisms that let users back out of
tentative operations or recover from errors.
– Entrusts other objects with the information it
needs to revert to a previous state without
exposing its internal structure and
representations.
UNIT-VII 348
L3
Forces
• Application needs to capture states at certain times
or at user discretion. May be used for:
– Undue / redo
– Log errors or events
– Backtracking
• Need to preserve encapsulation
– Don‘t share knowledge of state with other objects
• Object owning state may not know when to take
state snapshot.
UNIT-VII 349
L3
Motivation
UNIT-VII 350
L3
Motivation
Move
UNIT-VII 351
L3
Motivation
Memento pattern solves this problem as
follows:
• The editor requests a memento from the
object before executing move operation.
• Originator creates and returns a memento.
• During undo operation, the editor gives the
memento back to the originator.
UNIT-VII 352
L3
Applicability
UNIT-VII 353
L3
Structure
Originator Memento
Attribute Attribute caretaker
: :
state state
Operation: Operation:
SetMemento(Memento GetState( )
m) CreateMemento( ) SetState( )
state = m->GetState( )
UNIT-VII 354
L3
Participants
• Memento
– Stores internal state of the Originator object.
Originator decides how much.
– Protects against access by objects other than the
originator.
– Mementos have two interfaces:
• Caretaker sees a narrow interface.
• Originator sees a wide interface.
UNIT-VII 355
L3
Participants (continued)
• Originator
– Creates a memento containing a snapshot
of its current internal state.
– Uses the memento to restore its internal
state.
UNIT-VII 356
L3
Caretaker
UNIT-VII 357
L3
Event Trace
CreateMemento( )
new Memento
SetState( )
SetMemento(aMemento)
GetState( )
UNIT-VII 358
L3
Collaborations
UNIT-VII 359
L3
Consequences
UNIT-VII 360
L3
Consequences (continued)
Implementation
UNIT-VII 362
L3
Known Uses
• Memento is a 2000
film about Leonard
Shelby and his quest
to revenge the brutal
murder of his wife.
Though Leonard is
hampered with short-
term memory loss, he
uses notes and tatoos
to compile .
UNIT-VII 363
L3
UNIT-VII 364
L3
Related Patterns
• Command
Commands can use mementos to maintain
state for undo mechanisms.
• Iterator
Mementos can be used for iteration.
UNIT-VII 365
L4
Observer Pattern
• Define a one-to-many dependency, all the
dependents are notified and updated
automatically
• The interaction is known as publish-
subscribe or subscribe-notify
• Avoiding observer-specific update protocol:
pull model vs. push model
• Other consequences and open issues
UNIT-VII 366
L4
Observer Pattern
• Intent:
– Define a one-to-many dependency between objects so that
when one object changes state, all its dependents are
notified and updated automatically
• Key forces:
– There may be many observers
– Each observer may react differently to the same notification
– The subject should be as decoupled as possible from the
observers to allow observers to change independently of
the subject
UNIT-VII 367
L4
Observer
• Many-to-one dependency between objects
• Use when there are two or more views on the same ―data‖
• aka ―Publish and subscribe‖ mechanism
• Choice of ―push‖ or ―pull‖ notification styles
Subject
attach(Observer) Observer
detach(Observer) update()
notify() forall o in observers
o.update()
ConcreteSubject ConcreteObserver
getState() update()
state=subject.getState();
UNIT-VII 369
L4
Observer:
Encapsulating Control Flow
Name: Observer design pattern
Problem description:
Maintains consistency across state of one Subject and many Observers.
Solution:
A Subject has a primary function to maintain some state (e.g., a data
structure). One or more Observers use this state, which introduces
redundancy between the states of Subject and Observer.
Observer invokes the subscribe() method to synchronize the state.
Whenever the state changes, Subject invokes its notify() method to
iteratively invoke each Observer.update() method.
UNIT-VII 369
L4
Observer:
Class Diagram
Subject subscribers Observer
1 *
subscribe() update()
unsubscribe()
notify()
ConcreteSubject ConcreteObserver
state observeState
getstate() update()
setstate()
UNIT-VII 370
L4
Observer:
Consequences
Consequences:
Decouples Subject, which maintains state, from Observers,
who make use of the state.
Can result in many spurious broadcasts when the state of
Subject changes.
UNIT-VII 371
L4
s e tS ta te ( )
n o ti fy ( )
u p d a t e( )
g etS ta te ( )
u p d a t e( )
g e tS ta te ( )
UNIT-VII 372
L4
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
UNIT-VII 374
L4
Observer Pattern [3]
observers
Subject Observer
attach (Observer) Update()
detach (Observer)
For all x in observers{
Notify () x Update(); }
Concrete Observer
subject
Concrete Subject Update()
GetState() observerState
SetState()
observerState=
subjectState subject getState();
UNIT-VII 375
L4
SetState()
Notify()
Update()
GetState()
Update()
GetState()
UNIT-VII 376
L4
protected:
observer ();
};
Note the support for multiple subjects.
UNIT-VII 377
L4
protected:
Subject ();
private:
List <Observer*> *_observers;
};
UNIT-VII 378
L4
}
void Subject :: Notify (){
ListIterator<Observer*> iter(_observers);
for ( iter.First(); !iter.IsDone(); iter.Next()) {
iter.CurrentItem() -> Update(this);
}
UNIT-VII 379
L4
UNIT-VII 380
L4
ClockTimer :: Tick {
Notify();
UNIT-VII 381
L4
UNIT-VII 382
L4
_subjectAttach(this);
DigitalClock ::~DigitalClock() {
_subject->Detach(this);
UNIT-VII 383
L4
UNIT-VII 384
L4
UNIT-VII 385
L4
UNIT-VII 387
Unit-5 part-1
behavioural patterns part-2(contd)
L5
STATE Pattern
By :
Raghavendar Japala
UNIT-VII 389
L5
General Description
• A type of Behavioral pattern.
UNIT-VII 391
L5
Example I
water StateOfWater
state variable increaseTemp()
decreaseTemp()
increaseTemp()
decreaseTemp()
UNIT-VII 392
L5
How is STATE pattern
implemented ?
•―
Context‖ class:
Represents the interface to the outside world.
•―
State‖ abstract class:
Base class which defines the different states of
the ―
state machine‖.
•―Derived‖ classes from the State class:
Defines the true nature of the state that the state
machine can be in.
UNIT-VII 393
L5
Example II
MyMood MoodState
state variable
doSomething()
Client
doSomething()
UNIT-VII 395
L5
Pattern: Strategy
objects that hold alternate algorithms to solve a
problem
UNIT-VII 397
L6
Strategy pattern
• pulling an algorithm out from the object that contains it, and
encapsulating the algorithm (the "strategy") as an object
• each strategy implements one behavior, one implementation of how to
solve the same problem
– how is this different from Command pattern?
• separates algorithm for behavior from object that wants to act
• allows changing an object's behavior dynamically without extending /
changing the object itself
• examples:
– file saving/compression
– layout managers on GUI containers
– AI algorithms for computer game players
UNIT-VII 398
L6
// setting a strategy
player1.setStrategy(new SmartStrategy());
// using a strategy
Card p1move = player1.move(); // uses strategy
UNIT-VII 399
L6
Strategy:
Encapsulating Algorithms
Name: Strategy design pattern
Problem description:
Decouple a policy-deciding class from a set of mechanisms, so
that different mechanisms can be changed transparently.
Example:
A mobile computer can be used with a wireless network, or
connected to an Ethernet, with dynamic switching between
networks based on location and network costs.
UNIT-VII 400
L6
Strategy:
Encapsulating Algorithms
Solution:
A Client accesses services provided by a Context.
The Context services are realized using one of several
mechanisms, as decided by a Policy object.
The abstract class Strategy describes the interface that is common
to all mechanisms that Context can use. Policy class creates a
ConcreteStrategy object and configures Context to use it.
UNIT-VII 401
L6
Strategy Example:
Class Diagram for Mobile Computer
Application LocationManager
NetworkInterface
NetworkConnection
open()
send() close()
setNetworkInterface() send()
Context Strategy
contextInterface() algorithmInterface()
ConcreteStrategy1 ConcreteStrategy2
UNIT-VII 403
L6
Strategy:
Consequences
Consequences:
ConcreteStrategies can be substituted transparently
from Context.
Policy decides which Strategy is best, given the current
circumstances.
New policy algorithms can be added without modifying
Context or Client.
UNIT-VII 404
L6
Strategy
• You want to
– use different algorithms depending upon the context
– avoid having to change the context or client
• Strategy
– decouples interface from implementation
– shields client from implementations
– Context is not aware which strategy is being used;
Client configures the Context
– strategies can be substituted at runtime
– example: interface to wired and wireless networks
UNIT-VII 405
L6
Strategy
• Make algorithms interchangeable---‖changing the guts‖
• Alternative to subclassing
• Choice of implementation at run-time
• Increases run-time complexity
Context Strategy
ContextInterface() Operation()
ConcreteStrategy1 ConcreteStrategy2
Operation() Operation()
UNIT-VII 406
L7
UNIT-VII 407
L7
UNIT-VII 408
L7
Introduction
UNIT-VII 409
L7
UNIT-VII 410
L7
UNIT-VII 411
L7
UNIT-VII 412
L7
UNIT-VII 413
L7
ConcreteClass
hookMethod1()
hookMethod2()
UNIT-VII 414
L7
UNIT-VII 415
L7
y = sin x
UNIT-VII 417
L8
Pattern Hatching
Visitor pattern
visited.accept(this);
Visited
Visitor v.visit(this);
instance
UNIT-VII 418
L8
Pattern Hatching
Visitor Pattern
Class Visitor { void Visitor::visit (File* f)
public: {f->streamOut(cout);}
Visitor();
void visit(File*); void Visitor::visit (Directory* d)
void visit(Directory*); {cerr << “no printout for a
directory”;}
void visit (Link*);
};
void Visitor::visit (Link* l)
{l->getSubject()->accept(*this);}
UNIT-VII 419
L9
References
• Java API pages
– http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.html
– http://java.sun.com/j2se/1.4.2/docs/api/java/util/Iterator.html
– http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Container.html
– http://java.sun.com/j2se/1.4.2/docs/api/java/awt/LayoutManager.html
– http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JScrollPane.html
UNIT-VII 420
Unit-5 part-1
behavioural patterns part-2(contd)
S. No TOPIC PPT Slides
2 A Brief History
4 A Parting Thought.
7 Review Unit-V
UNIT-VIII 422
L1
UNIT-VIII 423
L1
A common design vocabulary
1. Studies of expert programmers for conventional languages have shown that
knowledge and experience isn‘t organized simply around syntax but in larger
conceptual structures such as algorithms, data structures and idioms [AS85,
Cop92, Cur89, SS86], and plans for fulfilling a particular goal [SE84].
2. Designers probably don‘t think about the notation they are using for recording
the designing as much as they try to match the current design situation against
plans, data structures, and idioms they have learned in the past.
3. Computer scientists name and catalog algorithms and data structures, but we
don‘t often name other kinds of patterns. Design patterns provide a common
vocabulary for designers to use to communicate, document, and explore
design alternatives.
UNIT-VIII 424
L1
A document and learning aid
1. Knowing the design patterns makes it easier to understand
existing systems.
2. Most large object-oriented systems use this design patterns
people learning object-oriented programming often complain
that the systems they are working with use inheritance in
convoluted ways and that it is difficult to follow the flow of
control.
3. In large part this is because they do not understand the design
patterns in the system learning these design patterns will help
you understand existing object-oriented system.
UNIT-VIII 425
L1
An adjacent to existing methods
1. Object-oriented design methods are supposed to promote good design, to teach
new designers how to design well, and standardize the way designs are developed.
3. Design methods usually describe problems that occur in a design, how to resolve
them and how to evaluate design. But then have not been able to capture the
experience of expert designers.
4. A full fledged design method requires more kinds of patterns than just design
patterns there can also be analysis patterns, user interface design patterns, or
performance tuning patterns but the design patterns are an essential part, one that‘s
been missing until now.
UNIT-VIII 426
L1
UNIT-VIII 427
L1
UNIT-VIII 429
L2
UNIT-VIII 430
L2
UNIT-VIII 431
L2
Grand‘s Classifications of
Design Pattern
• Fundamental patterns
• Creational patterns
• Partitioning patterns
• Structural patterns
• Behavioral patterns
• Concurrency patterns
UNIT-VIII 432
L3
His work has inspired time and again. So it‘s fitting worth
while To compare our work to his.
UNIT-VIII 433
L3
UNIT-VIII 434
L3
UNIT-VIII 435
L3
Alexander‘s Pattern Languages
There are many ways in which our work is like Alexander's
Both are based on observing existing systems and looking for patterns in them.
But there are just as many ways in which our work different.
People have been making buildings for thousands of years, and there are many
classic examples to draw upon. We have been making Software systems for a
Alexander gives an order in which his patterns should be used; we have not.
UNIT-VIII 436
Alexander‘s patterns emphasize the problems they adderss ,
L3
When Alexander claims you can design a house simply applying his patterns one after
Another ,he has goals similar to those of object-oriented design methodologies who
In fact ,we think it‘s unlikely that there will ever be a compete pattern language for soft
-ware.
UNIT-VIII 437
L3
A Parting Thought.
The best designs will use many design patterns that dovetail
Dense.
It is not profound. but it is also possible to put pattern‘s together
UNIT-V 438