Design Patterns
Design Patterns
in JNTU World
ld
11.Class Time Table
or
12.Individual Time Table
W
NPTEL class schedule
Date Teaching
No of
TU
SNO Unit No Topic Covered aids used
Periods
LCD/OHP/BB
1. UNIT-1 What is a Design Pattern? 1 BB
2. Describing Design Patterns, 1 BB
3. Organizing The Design Catalog 1 BB
4. How Design Patterns Solve Design 1 BB
Problems
5. How To Select A Design Pattern, 1 BB
JN
ld
10. Assignment test 1
11. UNIT-2 Designing a Document Editor 1 BB
12. Design problems, Document Structure 1 BB
13. Formatting , Embellishing the User 1 BB
or
Interface
14. Supporting , Multiple Look and Feel 1 BB/OHP
Standards
15. Supporting Multiple Window Systems 1 BB
16. User Operations Spell Checking And 1 BB
Hyphenation , Summary
W
17. Tutorial class/(NPTEL CLASS) 1 BB
18. Assignment test 1
19. UNIT-3 Creational patterns 1 BB
20. Abstract Factory 1 BB/OHP
21. Builder, Factory Method 1 BB
22. Prototype 1 BB
TU
23. Singleton 1 BB
24. Discussion Of Creational Patterns 1 BB
25. Tutorial class/(NPTEL CLASS) 1 BB
26. UNIT-5 Structural pattern part-I 1 BB
27. Adapter 1 BB
28. Bridge 1 BB
29. Composite 1 BB/OHP
JN
ld
Decorator
34. Acade 1 BB
35. Flyweight 1 BB
36. Proxy. 1 BB/OHP
37. Tutorial class/(NPTEL CLASS) 1 BB
or
38. Assignment test 1
39. UNIT-6 Behavioral patterns part-I 1 BB
40. Chain Of Responsibility 1 BB
41. Command, 1 BB
42. Interpreter 1 BB
W
43. Iterator 1 BB/OHP
44. Tutorial class/(NPTEL CLASS) 1 BB
45. Assignment test 1
46. UNIT-7 Behavioral patterns part-II 1 BB
47. Mediator 1 BB
48. Memento 1 BB
49. State , Strategy 1 BB
TU
50. Template, Method 1 BB
51. Visitor, 1 BB
52. Discussion of Behavioral patterns 1 BB
53. Tutorial class/(NPTEL CLASS) 1 BB
54. Assignment test 1
55. UNIT-8 What To Expect From Design Patterns 1 BB
JN
58. An Invitation 1 BB
59. 1 BB/OHP
ld
A parting Thought
60. Tutorial class/(NPTEL CLASS) 1 BB
61. Assignment test 1 BB
62. Solve University questions 1 BB
Total number of Classes required 62
or
W
TU
JN
15.Detailed Notes
ld
S
l
i
d
or
e
Design Patterns
1
Elements of Reusable
W
Object-Oriented Software
Authors
ld
l
i
UNIT-----------1
d
e
or
2
INTRODUCTION
W
P-2 Patterns I
TU
JN
ld
l
i
d
Design patterns describes simple and elegant solutions
e to specific problems in object-oriented software design.
or
3
W P-3 Patterns I
TU
JN
ld
l Authors definition of Design Patterns
i
d The design patterns are descriptions of
e
communicating objects and classes that are
or
customized to solve a general design
4
problem in a particular context.
OR
W
A Design Pattern is essentially a description of a
commonly occurring object-oriented design
problem and how to solve it
TU
P-4 Patterns I
JN
ld
l
i Four essential elements of a pattern
d
e Pattern Name
or
It is a handle we can use to describe a design problem, its
solutions, and consequences in a word or two.
5
It gives higher level abstraction.
Finding good names has been one of the hardest parts of
developing out catalog.
W
Problem
It describes when to apply the pattern.
It explains the problem and context.
It describes how to represent algorithms as objects
TU
P-5 Patterns I
JN
ld
l
i
d Solution
e It describes the elements that make up the design, the
or
relationships, responsibilities and collaborations.
The solution doesnt describe a particular concrete design or
6 implementation, because a pattern is like a template that can be
applied in many different situations
Pattern provides a general arrangement of elements to solve it
W
Consequences
These are the results and trade offs of applying the pattern
When describing design decisions, these are critical for
evaluating design alternatives and for understanding the costs
and benefits of applying the pattern.
TU
P-6 Patterns I
JN
ld
l A design pattern represents a widely accepted solution to a recurring
design problem in OOP
i
d
e
or
Each design pattern focuses on a particular object-oriented design
problem
7
W
TU
P-7 Patterns I
JN
ld
l Design Patterns in Smalltalk MVC
or
object, the View is its screen presentation, and the Controller defines
the way the user interface reacts to user input
8
W P-8 Patterns I
TU
JN
ld
l
i The example reflects a design that decouples views from
models
d
e
or
9
W P-9
TU
JN
ld
l
i Describing Design patterns
d Each pattern is divided into sections according to the following
template
e
or
Pattern Name and Classification
The patterns name conveys the essence of the pattern succinctly.
1 A good name is vital because it becomes the design vocabulary
0 Intent
A short statement that answers the following questions
W
What does the design pattern do?
What is its rationale and intent?
What particular design issue or problem does it address?
P-10
TU
JN
ld
l
i
d Also known as
e Other names for the pattern, if any
or
Motivation
1
A scenario that illustrates a design problem and how the class and
object structures in the pattern solve the problem
1
Applicability
W
What are the situations in which the design pattern can be
applied? What are examples of poor designs that the pattern can
address? How can you recognize these situations?
P-11 Patterns I
TU
JN
ld
l
i
d Structure
e A graphical representation of the classes in the pattern using a
or
notation based on the Object Modeling Technique (OMT).
1
We use interaction diagrams to illustrate sequences of requests
2 and collaborations between objects.
Participants
W
The classes and/or objects participating in the design pattern and
their responsibilities
P-12 Patterns I
TU
JN
ld
l
i
d Collaborations
e How the participants collaborate to carry out their responsibilities
or
Consequences
1 How does the pattern support its objectives? What are the trade-
3 offs and results of using the pattern? What aspect of system
structure does it let you vary independently?
W
Implementation
What pitfalls, hints, or techniques should you be aware of when
implementing the pattern? Are there any language specific issues?
TU
P-13 Patterns I
JN
ld
l
i
d Sample Code
e Code fragments that illustrate how you might implement the
or
pattern in C++ or Smalltalk
1 Known Uses
4 Examples of the pattern found in real systems. At least 2 examples
from different domains
W
Related patterns
What design patterns are closely related to this one? What are the
important differences? With which other patterns should this one
be used?
TU
P-14 Patterns I
JN
ld
l
i Patterns
d This book defined 23 patterns, classified into three
e categories.
or
Creational patterns, which deal with the process of object
creation.
1
Structural patterns, which deal primarily with the static
5 composition and structure of classes and objects.
Behavioral patterns, which deal primarily with dynamic
W
TU interaction among classes and objects.
P-15 Patterns I
JN
ld
l
i Catalog of Design Patterns
d Creational Patterns Behavioral Patterns
Abstract Factory Chain of Responsibility
e
or
Builder Command
Factory Method Interpreter
Prototype Iterator
1 Singleton Mediator
W
Composite Strategy
Decorator Template Method
Faade Visitor
Flyweight
Proxy
TU
P-16 Patterns I
JN
ld
l
Organizing the catalog
i
Purpose
d
e Creational Structural Behavioral
or
Class Factory Method Adapter(Class ) Interpreter
Template Method
1 Scope
Object Abstract Factory Adapter (Object) Chain of
7 responsibility
Builder Bridge
Prototype Composite Command
W
Singleton Decorator Iterator
Faade Mediator
Flyweight Memento
proxy Observer
State
Strategy
visitor
P-17
TU
JN
ld
l We classify design patterns by two criteria
i
d
Purpose scope
e
or
Reflects what a pattern does. Specifies whether the pattern
1 applies primarily to classes or to
8 objects.
W
Class patterns deal with
Creational relationships between
Structural , Behavioral purpose classes and their subclasses.
Object patterns deal with
object relationships, which can be
P-18 Patterns I
changed at run-time and are more
dynamic.
TU
JN
S
How design patterns solve design problems
ld
l
i
1) Finding Appropriate Objects
d
An object packages both data and the procedures(methods or
e operations) that operate on the data
or
1 An object performs an operation when it receives a request from a
client
9
W
are the only way to change an objects internal data, then object
internal state is said to be encapsulated (i.e. objects representation
is invisible from the outside).
TU
P-19
JN
ld
l
i
d How to Create an object
e write problem statement find out nouns and verbs and create
or
corresponding classes and operations .
2
Design patterns help you identify less-obvious
0 abstractions and the objects that can capture them.
W
The State (305) pattern represents each state of an entity
as an object.
TU
P-20
JN
ld
l
i
d 2) Determining object Granularity
How do we decide what should be an object?
e
or
Subsystems can be represented as objects (Facade)
2 Objects of finest granularity (Flyweight)
Objects responsibilities can create other objects (Abstract
1
Factory, Builder)
3) Specifying object interfaces
W
An operation can be specified as operation name, parameters
and its return value is known as signature
The set of all signatures defined by an objects operations is
called the interface to the object.
P-21 Patterns I
TU
JN
S
A type is a name used to denote a particular interface
ld
l
Eg.Window obj1;
i
d A type is a subtype of another if its interface contains the interface
e of its supertype.
or
The runtime association of a request to an object and one of its
operations is known as dynamic binding.
2 Dynamic binding lets us to substitute objects that have identical
2 interfaces for each other at runtime is called as Polymorphism.
W
Design patterns help you define interfaces by identifying
their key elements and the kinds of data that get sent across
an interface.
A design pattern might also
tell you what not to put in the interface.
TU
P-22
JN
ld
l
i 4) Specifying Object Implementations
d
e An objects implementation is defined by its class. The class
or
specifies the objects internal data and representation and
defines the operations the object can perform
2 Class can be rendered as
3 Class name
Operation1()
W
Instantiator instantiatee
Type operation2() ..
InstanceVariable1
Type
InstanceVariable2 ..
P-23 Patterns I
TU
JN
ld
l
i Class inheritance
d
Parent Class
e
or
Operation()
2
4
Sub class
W P-24 Patterns I
TU
JN
ld
l
i
d An abstract class is one whose main purpose is to define a
common interface for its subclass(it defers in implementation to
e operations defined in subclass).
or
It cannot be instantiated
The operations that an abstract class declares but doesnt
2 implement are called abstract operations.
5 (the names in italic indicates a class or operation as abstract)
Classes that are not abstract are called concrete classes.
W
A class may override an operation defined by its parent class
A Mixin class is a class thats intended to provide an optional
interface or functionality to other classes(it is an abstract class
that can be instantiated).
P-25 Patterns I
TU
JN
ld
l
i
d Class Vs Interface inheritance
e The difference between objects class and type is class defines
or
the objects internal state and the implementation of its
operations, in contrast type refers to its interface.
2 Class inheritance defines an objects implementation in terms of
6 another objects implementation(mechanism for code and
representation sharing), in contrast interface inheritance
W
describes when an object can be used in place of another.
Programming to an interface, not an Implementation
It is the principle of reusable OOD.
P-26 Patterns I
TU
JN
ld
l
i 5) Putting reuse mechanisms to work
d
e It is easy to know class, interface, object etc., but applying
or
them to build flexible, reusable s/w and Design Patterns can
show how
2 Inheritance versus Composition
7 White-box reuse with inheritance, the internals of parent
classes are often visible to subclasses (visibility).
Black-box reuse object composing, i.e., objects that
W
composed have well defined interfaces
Disadvantages with class inheritance
Change the implementations inherited from parent classes at run-time is
not possible.
Parent classes often define at least part of their subclasses physical
representation.
TU
P-27
JN
S
Delegation
ld
l
i
It is a way of making composition as powerful for reuse as
inheritance
d
The following diagram depicts the Window class
e
or
delegating its Area operation to a Rectangle instance
2
8
Rectangle
W
Window rectangle Area()
Area()
Width
height
TU
P-28 Patterns I
JN
ld
l
i
d Advantage of delegation it makes it easy to compose
e behaviors at run-time and to change the way they are
or
composed
2
Disadvantage it shares with other techniques that make
software more flexible through object composition (I.e.,
9
understanding s/w, runtime inefficiencies)
W
Several design patterns use delegation.
The State (338), Strategy (349), andVisitor (366)
patterns depend on it.
TU
P-29 Patterns I
JN
S
6) Relating run-time and compile time structures
ld
l
i compile time structure is static and runtime structure is
dynamic.
d
Acquaintance or Association
e
Acquaintance implies that an object merely knows of
or
another object.
3 Aggregation
0 Aggregation implies that one object owns or is responsible
for another object
W
:
TU
P-30
JN
ld
l In our diagrams, a plain arrowhead line denotes acquaintance. An
arrowhead line with a diamond at its base denotes aggregation
i
d
e
or
3 Many design patterns capture the distinction between compile-time
1 and run-time structures explicitly.
Composite(183) and Decorator (196) are especially useful for
W
building complex run-time structures.
Observer (326) involves run-time structures that are often hard to
understand unless you know the pattern
TU
P-31
JN
ld
l
i 7) Designing for change
d A design that doesn't take change into account risks major
e redesign in the future.
or
We must consider how the system might need to change over its
lifetime
3 These changes leads to class redefinition and reimplementation,
client modification, and retesting
2
Some common causes of redesign
Creating an object by specifying a class explicitly. (Abstract Factory,
W
Factory Method, Prototype)
Dependence on hardware and software platform. (Chain of
responsibility, Command)
Dependence on object representations or implementations. (Abstract
Factory, Bridge)
Algorithmic dependencies
Tight coupling. etc.,
TU
P-32
JN
ld
l
i Role played by Design patterns
d Application Programs
e When building application program such as a document editor
or
or spreadsheet then internal reuse, maintainability, and
extensions are high priorities.
3 design patterns makes it easy to have all these without any side
effects.
3
Toolkits
W
A toolkit is a set of related and reusable classes designed to
provide useful, general-purpose functionality.
Frameworks
A framework is a set of cooperating classes that makeup a
reusable design for a specific class of software.
TU
P-33 Patterns I
JN
ld
l
i How to select a Design Pattern
d Consider how design patterns solve design problems.
e
or
Scan intent sections.
W
Examine a cause of redesign
ld
l
i How to use a Design Pattern
d Read the pattern once through for an overview
e Go back and study the structure, participants, and
or
collaborations sections.
Look at the sample code section to see a concrete example of
3 the pattern in code
5
Choose names for pattern participants that are meaningful in
the application context
Define the classes
W
Define application- specific names for operations in the
pattern.
Implement the operations to carry out the responsibilities
and collaborations in the pattern
TU
P-35 Patterns I
JN
ld
EDITOR
Slide 1
or
UNIT = 2
W
A case study:
Designing a Document Editor
TU
JN
Slide 2
ld
This chapter presents a case study in the design of a
"What-You-See-Is-What-You-Get" (or "WYSIWYG") document
editor called Lexi.
or
We'll see how design patterns capture solutions to design
problems in Lexi and applications like it.
W
Figure depicts Lexi's user interface.
TU
P-2
JN
Slide 3
ld
or
W P-3
TU
JN
Slide 4
Design Problems
ld
Document structure
The choice of internal representation for the document affects
nearly every aspect of Lexis design.
or
Editing, formatting, displaying, and textual analysis will
require traversing the representation.
Formatting
How does Lexi actually arrange text and graphics into lines
and columns?
W
What objects are responsible for carrying out different
formatting policies?
Embellishing the user interface
Lexis user interface includes scroll bars, borders, and drop
shadows that embellish (Decorating) the WYSIWYG
document interface.
TU
P-4
Patterns I
JN
Slide 5
ld
Supporting multiple look and feel standards
Lexi should adapt easily to different look and feel standards
such as Motif and Presentation Manager without major
or
modification.
Supporting multiple window systems
Different look and feel standards are usually implemented on
different window systems. Lexis design should be as
independent of the window system as possible.
User operations
W
User control Lexi through various user interfaces, including
buttons and pull-down menus.
P-5
Patterns I
TU
JN
Slide 6
ld
Spelling checking and hyphenation
How does Lexi support analytical operations such as
checking for misspelled words and determining hyphenation
or
points?
W P-6
TU
JN
Slide 7
1) Document structure
ld
Recursive composition
A common way to represent hierarchically structured information is
through a technique called recursive composition
or
As a first step, we can tile a set of characters and graphics from left
to right to form a line in the document.
W
columns can form a page, and so on.
P-7
Patterns I
TU
JN
Slide 8
ld
or
W Patterns I
P-8
TU
JN
Slide 9
ld
or
W Patterns I
P-9
TU
JN
Slide 10
ld
Glyphs
A glyph is an abstract class for all objects that can appear in a
document structure.
or
Its subclasses define both primitive graphical elements (char
and images) and structural elements (rows and columns)
Glyph have 3 basic responsibilities
o How to draw themselves
o What space they occupy and
o Their children and parent
W Patterns I
P-10
TU
JN
Slide 11
ld
or
W Patterns I
P-11
TU
JN
Slide 12
ld
Composite pattern
We can use recursive composition to represent any
potentially complex hierarchical structure.
or
The composite pattern captures the essence of recursive
composition in object-oriented terms
W
TU
P-12
Patterns I
JN
Slide 13
2) Formatting
ld
Formatting or Line Breaking Lexi must break text into lines,
lines into columns, and columns into pages, taking into account the
users higher level desires.
or
In this case we are considering formatting as breaking a
collection of glyphs into lines.
W
formatting quality and formatting speed.
P-13
Patterns I
TU
JN
Slide 14
ld
Define a separate class hierarchy for objects that encapsulate
formatting algorithms
or
wide range of formatting algorithms, and each subclass will
implement the interface to carryout a particular algorithm
W Patterns I
P-14
TU
JN
Slide 15
ld
Compositor and composition
Well define Compositor class for objects that can encapsulate
a formatting algorithm.
or
The glyphs it formats are the children of a special Glyph
subclass called Composition
When the composition needs formatting, it calls its
compositor's Compose operation
The compositor in turn iterates through the
W
composition's children and inserts new Row and
Column glyphs according to its line breaking algorithm.
TU
P-15
Patterns I
JN
Slide 16
ld
or
W
TU
P-16
Patterns I
JN
ld
In to the object structure appear with gray backgrounds in the figure.
or
W Figure 2.6: Object structure reflecting compositor-directed
linebreaking
TU
P-17
Patterns I
JN
Slide 18
ld
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.
or
We can add new Compositor subclasses without touching the
glyph classes, and vice versa.
Strategy pattern
Encapsulating an algorithm in an object is the intent of the
strategy pattern.
W
The key to applying the Strategy pattern is designing
interfaces for the strategy and its context that are
general enough to support a range of algorithms.
TU
P-18
Patterns I
JN
Slide 19
3) Embellishing the User Interface
ld
We consider 2 types of embellishments
1. Border 2. Scroll bars
The first adds a border around the text editing area to
or
demarcate the page of text.
The second adds scrollbars that let the user view
different parts of the page.
Transparent Enclosure to experiment with
W
different alternatives, and it keeps clients free of
embellishment code.
Mono Glyph
A subclass of glyph called Mono Glyph serve as an abstract
class for embellishment glyphs.
TU
P-19
JN
Slide 20
ld
Mono Glyph stores a reference to a component and forwards all
requests to it
or
For example, MonoGlyph implements the Draw operation
like this:
W
}
Decorator pattern
Decorator pattern captures class and object relationships
that support embellishment by transparent enclosure.
TU
P-20
Patterns I
JN
Slide 21
ld
or
W
TU
P-21
Patterns I
JN
Slide 22
ld
or
W
TU
P-22
Patterns I
JN
Slide 23
4)Supporting multiple look-and feel standards
ld
Achieving portability is a major problem in system
design
One obstacle to portability is the diversity of look and
or
feel standards
Our design goals are to make lexi conform to multiple
existing look and feel standards and to make it easy to
add support for new standards as they emerge and to
W
support the ultimate in flexibility (i.e., changing lexis
look and feel at runtime)
TU
P-23
Patterns I
JN
Slide 24
ld
Abstracting Object Creation
Lexis user interface is a glyph composed in other, invisible
glyphs like Row and Column.
or
The invisible glyphs compose visible ones like Button
and Character and lay them out properly.
Widgets is the term used for visible glyphs like buttons,
scroll bars and menus that act as controlling elements in a
W
user interface
Widgets might use simpler glyphs such as characters,
circles, rectangles, and polygons to present data.
TU
P-24
JN
Slide 25
ld
There are two types of widget glyph class with which to
implement multiple look and feel standards
or
A set of abstract Glyph subclasses for each
category of widget glyph.
Button is an abstract class that adds button-oriented operations;
A set of concrete subclasses for each abstract
W
subclass that implement different look and feel
standards.
For example, ScrollBar might have MotifScrollBar and PMScrollBar
subclasses that implement Motif and Presentation Manager-style scroll bar
TU
P-25
JN
Slide 26
ld
Factories and Product Classes
Factories create Product objects. The products that a factory
produces are related to one another.
or
Abstract Factory pattern
W
Factory Pattern.
Slide 27
ld
or
W
TU
P-27
JN
Slide 28
ld
or
W P-28
TU
JN
Slide 29
5) Supporting Multiple Window systems
ld
Can we use an Abstract Factory
Two different windows of different vendors may not have
same hierarchy. Hence we wont have a common abstract
or
product class for each kind of widget and abstract factory
pattern wont work
Encapsulating Implementation Dependencies
Window class encapsulates the functionalities i.e.
They provide operations for drawing basic geometric shapes.
W
They can iconify and de-iconify themselves.
They can resize themselves
They can (re)draw their contents on demand,
TU
P-29
JN
Slide 30
ld
The Window class must span the functionality of
windows from different window systems.
Let's consider two extreme philosophies:
or
Intersection of functionality
The window class interface provides only functionality thats
common to all window systems.
union of functionality
W
Create an interface that incorporates the capabilities of all
existing systems.
Extreme of any of the above is not a viable solution, so
our design will fall somewhere between the two
P-30
TU
Patterns I
JN
Slide 31
ld
or
W
TU
P-31
JN
Slide 32
ld
where does the real platform-specific window come in?
or
class and its subclasses, one version for each windowing platform.
W
We can configure window objects to the window system we want
simply by passing them the right window system-encapsulating
object.
We can even configure the window at run-time
TU
P-32
Patterns I
JN
Slide 33
ld
Window and WindowImp
or
WindowImp is an abstract class for objects that encapsulate
window system-dependent code.
We can easily extend the implementation hierarchy to support
new window systems.
W
TU
P-33
JN
Slide 34
ld
or
W
TU
P-34
Patterns I
JN
Slide 35
ld
Bridge Pattern
or
The relationship between Window and WindowImp is an example
of the Bridge pattern.
W
Our design criteria led us to create two separate class hierarchies, one
that supports the logical notion of windows,
And another for capturing different implementations of windows
TU
P-35
Patterns I
JN
Slide 36
6) User Operations
ld
Some user operations are
Creating a new document
Opening, saving, and printing an existing document
or
Cutting selected text out of the document and pasting it back in
Quitting the application etc.,
Lexi provides different user interfaces for these
operations.
W
But problem is, you can turn the page using either a page
button or a menu operation.
TU
P-36
JN
Slide 37
Encapsulating a request
ld
A Glyph subclass called MenuItem
Carrying out the request might involve an operation on one
object, or many operations on many objects.
or
But it cannot address
Undo / redo problem
Cant associate state with a function
Functions are hard to extend
We will encapsulate each request in a command object
W
Command class and subclasses
Command abstract class provides an interface for issuing a request.
Subclass of command implement this function (Execute() ) in
different ways to fulfill different requests.
Now MenuItem can store a command object that encapsulates a
request. P-37
TU
JN
Slide 38
ld
or
W Patterns I
P-38
TU
JN
Slide 39
ld
or
W Patterns I
P-39
TU
JN
Slide 40
undo ability
ld
Unexecute() operation which works reverse to Execute() to
accommodate undo/redo functions
Command history or list of commands
To accommodate undo/redo command history should be
or
maintained.
W
Each circle represents a Command object. In this case the user has
issued four commands
P-40
TU
JN
Slide 41
ld
To undo the last command, we simply call Unexecute on the most
recent command:
or
W Patterns I
P-41
TU
JN
Slide 42
ld
After unexecuting the command, we move the "present" line one
command to the left. If the user chooses undo again, the next-most
recently issued command will be undone in the same way, and we're
left in the state depicted here:
or
W
The number of levels is limited only by the length of the command
history P-42
TU
JN
Slide 43
ld
To redo the last undone command, we call Execute on the command
to the right of the present line:
or
W Patterns I
P-43
TU
JN
Slide 44
ld
Command pattern
or
which describes how to encapsulate a request.
The pattern also discusses undo and redo mechanisms built on the
basic Command interface.
W Patterns I
P-44
TU
JN
Slide 45
7) Spelling checking and Hyphenation
ld
This is a textual analysis, specifically checking for
misspellings and introducing hyphenation points where
needed for good formatting.
or
Here we could come across two problems
Accessing the information to be analyzed, which we have
scattered over the glyphs in the document structure and
Doing the analysis
Accessing Scattered Information
W
The text we need to analyze is scattered throughout a
hierarchical structure of glyph object
Some glyphs might store their children in linked lists, others
might use arrays, and still others might use more complex
data structures.
TU
P-45
Patterns I
JN
Slide 46
ld
So our access mechanism must accommodate differing data
structures and we must support different kinds of traversals such
as preorder, postorder, and inorder.
or
Encapsulating Access and Traversal
W
Void First(Traversal kind)
Void Next()
Bool IsDone()
Glyph* GetCurrent()
Void Insert(Glyph*)
TU
P-46
JN
Slide 47
ld
A better solution is to encapsulate the concept that
varies, in this case the access and traversal mechanisms
is Iterators.
or
Iterator class and subclasses
Well use an abstract class called Iterator to define a general
interface for access and traversal.
Concrete subclasses like ArrayIterator and ListIterator
implement the interface to provide access to arrays and lists
W
Notice that we've added a CreateIterator abstract operation to the
Glyph class interface to support iterators..
TU
P-47
JN
Slide 48
ld
or
W
TU
P-48
JN
Slide 49
ld
Iterator Pattern
This pattern captures these techniques for supporting access
and traversal over object structures
Traversal versus Traversal Actions
or
Analysis and Traversal should be separate
preorder traversal is common to many analyses,
including spelling checking, hyphenation, forward
search, and word count
W
Analysis must be able to distinguish different kinds of glyphs
P-49
Patterns I
TU
JN
Slide 50
ld
Visitor class and subclasses
It applies a hyphenation algorithm to determine the potential
hyphenation points in the word, if any.
or
Then at each hyphenation point, it inserts a discretionary glyph into
the composition.
Discretionary glyphs are subclass Of Glyph.
W
depending on whether or not it is the last character on a line.
If it's the last character, then the discretionary looks like a
hyphen;
P-50
Patterns I
TU
JN
Slide 51
ld
or
W Patterns I
P-51
TU
JN
UNIT-III
ld
Unit-3
or
Creational Design Pattern
W Factory
Singleton
TU
Abstract Factory
Prototype
JN
ld
or
W
Factory Design Pattern
TU
JN
Factory
Design Purpose
ld
Create individual objects in situations where
or
the constructor alone is inadequate.
W
Design Pattern Summary
T U
Use methods to return required objects.
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
public static void main(String[] args)
or
{
RequiredClass instanceOfRequiredClass = MyClass.getNewInstanceOfRequiredClass();
} // End main
W
TU
JN
ld
Client RequiredClass
or
create object
W
MyClass
createObjectOfRequiredClass(): RequiredClass
U
Factory design pattern
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
Design Goal At Work: Reusability and Corrrectness
W
We want to write code about automobiles in general: Code
that applies to any make, exercised repeatedly (thus reliably).
U
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
Application
Automobile of Factory
or
createAutomobile(): Automobile design
pattern
Ford
W
createAutomobile()
Toyota
createAutomobile()
T U
create object create object
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Example Code
ld
class Ford extends Automobile
{
or
static Automobile createAutomobile()
{
W
return new Ford();
} // End createAutomobile
TU
} // End class
JN
ld
createObjectOfRequiredClass()
or
RequiredClass()
W
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
Word that was entered
or
W
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
Design Goals At Work: Correctness and Reusability
W
We want to separate the code common to all types of
customers. We want to separate the specialized code that
generates e-mail for each type of customer. This makes it
U
easier to check for correctness and to reuse parts.
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
<<abstract>>
Customer
getMessage()
or
W
Frequent Returning Curious Newbie
getMessage() getMessage() getMessage() getMessage()
U
Client
sendMessage()
T
setup
JN
MailGenerationApplication MailMessage
getCustomerTypeFromUser() text
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Client
ld
create
object
or
Component
getGraphics(): Graphics Graphics
W
Factory design pattern
U
public static Box createVerticalBox()
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
W
7.2 - Singleton Design Pattern
TU
JN
ld
or
Key Concept: Singleton Design Pattern
W
-- when a class has exactly one instance.
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
Ensure that there is exactly one instance of a
class S. Be able to obtain the instance from
or
anywhere in the application.
W
Design Pattern Summary
U
Make the constructor of S private; define a
T
private static attribute for S of type S; define a
JN
ld
or
Design Goal At Work: Correctness
W
Singleton enforces the intention that only one
User object exists, safeguarding the application
from unanticipated User instance creation.
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
User mainUser = User.getTheUser();
W
TU
JN
ld
or
Singleton Design Pattern
MyClass
W
singletonOfMyClass
getSingletonOfMyClass(): MyClass
static
1
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
MyClass of type MyClass
or
private static MyClass singletonOfMyClass = new MyClass();
1. Make the constructor of MyClass private
W
private MyClass() { /* . constructor code . */ };
1. Define a public static method to access the
U
member
public static MyClass getSingletonOfMyClass()
T
{
JN
return singletonOfMyClass;
}
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Application of Singleton
to Experiment Example
ld
Experiment
theExperiment: Experiment
or
theExperiment
Client analyze()
getTheExperiment(): Experiment static
reportResults()
W
1
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
Key Concept: Singleton Design Pattern
When a class must have exactly one instance,
W
make the constructor private and the instance
a private static variable with a public accessor.
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Example Code
ld
public class Runtime
{
private static Runtime currentRuntime = new Runtime();
or
// Returns the runtime object associated with the current
// Java application.
W
public static Runtime getRuntime()
{
return currentRuntime;
}
TU
private Runtime() { }
}
JN
ld
or
W
7.3 - Abstract Factory Design Pattern
TU
JN
bstract Factory
Design Purpose
ld
Provide an interface for creating families of
or
related or dependent objects without
W
specifying their concrete classes.*
Design Pattern
U
Capture family creation in a class containing
T
a factory method for each class in the family.
JN
* Gamma et al
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
---> Enter title: ---> Enter text:
My Life I grew up playing in the woods
or
---> Enter Heading or -done: ---> Enter Heading or -done:
W
Birth Adulthood
.
---> Enter text:
U
I was born in a small mountain hut ---> Enter Heading or -done:
.
T
-done
JN
ld
>> Enter the style you want displayed: >> Enter the style you want displayed:
big small
Option 1 Option 2
or
My Life
----- Title: MY LIFE -----
Birth
W
Section 1. --- BIRTH --- I was born in a mountain hut .
I was born in a mountain hut .
U Youth
Section 2. --- YOUTH --- I grew up sturdy
T
I grew up sturdy
JN
Adulthood
Section 3. --- ADULTHOOD ---
.
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
Client
or
AbstractFactory
Ensemble getAPart1Object()
setAbstractFactory() getAPart2Object()
W
doAFunction()
U
Abstract Factory* StyleAFactory StyleBFactory Style.
T
* relationships within pattern application not shown
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
Document 1 Style
or
setStyle()
display()
W
SmallStyle LargeStyle
U
.......
Client Application of Abstract Factory
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
abstractFactory 1 AbstractFactory
Ensemble getAPart1Object()
doAFunction() getAPart2Object()
ld
1..n 1..n
Part1 Part2 Part
or
W
Part1StyleA Part1StyleB Part2StyleA Part2StyleB
create
U
Abstract
T
Factory StyleAFactory StyleBFactory Style.
JN
Client
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Sequence
:Client abstractFactory :Ensemble
Diagram for
:StyleXFactory abstractFactory Abstract
ld
:AbstractFactory Factory
StyleXFactory()
Selecting
or
} astyle :Part_iStyleX
W
setAbstractFactory(abstractFactory)
doAFunction()
Assume that
getAPart_i()
}
U Creating a Part i object in
this method getAPart_i()
required style
requires a
T
Part_i object. Part_iStyleX()
JN
Virtual
function
property
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
Design Goals At Work: Correctness and Reusability
W
We want to separate the code parts that format the
document in each style. We also want to separate the
common document generation code. This facilitates
U
reusing parts and checking for correctness.
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
display()
) 0..n
0..n
or
value value value
Displayable
W
SmallHeading LargeHeading SmallTitle LargeTitle
display() display() display() display()
TU
create
SmallStyle LargeStyle
getAHeading() getAHeading()
Abstract Factory
getATitle() getATitle() Applied to Word
Processor
JN
Client
getStyleFromUser()
Adapted from Software Design: From Programming to
displayDocument() Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ImagePeer
ld
ToolKit
or
createButton() ImagePeer implementation 3
createImage() ButtonPeer
W
U ButtonPeer implementation 3
T
ConcreteToolkit1 ConcreteToolkit2 ConcreteToolkit3
JN
ld
abstractFactory 1 AbstractFactory
Ensemble getAPart1Object()
or
setStyleA() getAPart2Object()
setStyleB()
StyleAFactory
W StyleBFactory Style.
U
....
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
Key Concept: Abstract Factory Design Pattern
W
To design an application in which there are several
possible styles for a collection of objects, capture
styles as classes with coordinated factory methods.
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
W
7.4 - Prototype Design Pattern
TU
JN
Prototype
Design Purpose
ld
or
Create a set of almost identical objects
whose type is determined at runtime.
W
U Design Pattern
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Example:
A Selection
ld
or
W
TU
Furniture Furniture
Click on choice of desk: hardware
JN
color
type
Click on choice of storage:
colonial
Click on choice of chair:
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
A Simplified
Prototype
Example
ld
or
W
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Prototype Interface
With Clients
ld
Client
or
(optional part
W
Ensemble of interface)
createEnsemble()
Part1 Part2
U
clone() clone()
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Code Example
ld
or
OfficeSuite myOfficeSuite =
OfficeSuite.createOfficeSuite( myDesk, myChair, myStorage);
myGUI.add(myOfficeSuite);
W
myOfficeSuite.setBackground(pink);
TU
JN
ld
or
Ensemble myPartPrototype 1 MyPart
createEnsemble() clone(): MyPart
W
// To create a MyPart instance:
T U
MyPart p = myPartPrototype.clone();
MyPartStyleA MyPartStyleB
JN
clone() clone()
Code Example
ld
Ensemble EnsembleA Ensemble.createEnsemble(. . .);
or
W
// This code is inside the Ensemble class MyPart
anotherMyPart = MyPartPrototype.clone();
MyPart yetAnotherMyPart = MyPartPrototype.clone();
TU
JN
ld
// To create a Part1 object:
Part1 p1 = part1Prototype.clone();
.
Ensemble
or
createEnsemble() part1Prototype part2Prototype
1 1
W
Part1 Part2
U clone() clone()
ld
:PartN :PartNStyleB
or
createEnsemble()
W
clone()
U PartNStyleB()
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
style, any desk style, and any cabinet style
or
This is all done separately rather than have
to select an overall office style
W
Nevertheless, the client wants to keep a
single style of chair and a single style of
TU
desk throughout the office suite
JN
ld
or
Design Goals At Work: Correctness and Reusability
W
We want to isolate the parts pertaining to each type of
customer. We also want to isolate the common customer
code. This makes it easier to check the design and
U
implementation for correctness, and to reuse the parts.
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
OfficeProcess customerPrototype 1 Customer
or
doAProcess() clone(): Customer
W
T U
HiVolCustomer MedVolCustomer LoVolCustomer
clone() clone() clone()
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
(1) Class model: Class1 Class2
or
(2) c1 an instance of Class1: c1:Class1 c2:Class2
W
c1.clone should be as follows (deep clone):
TU
c1.clone:Class1 x*:Class2
c1.clone:Class1
* a clone of c2
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
Key Concept: Prototype Pattern
-- when designing for multiple instances
W
which are the same in key respects,
create them by cloning a prototype.
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
Structural Design Patterns
or
Facade
W
Decorator
Composite
TU
Adapter
Flyweight
JN
Proxy
ld
or
W
Faade Design Pattern
TU
JN
ld
or
Design Pattern Summary
W
Define a class (typically a singleton) that is
the sole means for obtaining functionality
U
from the package.
T
JN
ld
1 Faade
exposed
Client
or
cMethodOfFacade()
W
U 2
C
T
not exposed
myCMethod()
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
:Client singleton :C
ld
:Facade
cMethodOfFacade()
or
myCMethod()
W
(return if any)
(return if any)
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
MyGameEngine
or
MyGame
facade
MyGameCharacters
W
packages
MyGameCast
U
facade MyGameEnvironment
T
MyGameEnvironment
JN
facade
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
Design Goals At Work: Correctness and Reusability
W
Collecting customer-related classes in a package with a
clear interface clarifies the design, allows independent
verification, and makes this part reusable.
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
<<interface>> <<interface>>
ld
CustomerException getPersonalNote() getBalance()
getAccount( int )
or
framework
1..n
W
Using Faade to BankCustomer BankAccount
Access Bank
Customers IntroMessage
TU
package facade
BankCustomers
Client doDeposit( int amt, Customer cust, Account acc )
main() getBankAccount( Customer cust, int accNum )
JN
ld
or
Key Concept: Facade Design Pattern
W
-- modularizes designs by hiding
complexity (similar to the web services
U
provided by a web site)
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
W
Decorator Design Pattern
TU
JN
ld
or
Design Pattern Summary
W
Provide for a linked list of objects,
each encapsulating responsibility.
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
Component 1
Client add( Component )
or
doAction()
Substance
W Decoration
objDecorated
T U doAction() doAction()
client:Client Linked
Objects in
ld
decoration1:Decoration Decorator
or
decoration1.objectDecorated:Decoration
W
U :Decoration
.:Substance
T
This list is created backwards
so that the last decoration
JN
ld
:Decoration :Decoration
or
doAction()
doAction()
W
doAction()
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Decorator Applied to
Customer / Accounts AttemptToAddBadBankingComponentException
Example
ld
<<interface>> Means exactly
BankingComponent 1 one aggregate
Client add( Component ) per account
or
describe()
W
nextComponent
Setup Customer Account
main() describe() describe()
T U
CheckAccount SavingsAccount CDAccount
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
ConstructionComponent
Client add( Component )
or
showPrice()
W
nextComponent
Setup ConstrJob ConstrMaterial
add() showPrice()
showPrice()
T U
Window Door Beam
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
InputStream InputStreamReader BufferedReader
W
U
BufferedReader bufReader = new BufferedReader
(new InputStreamReader(System.in) );
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
Key Concept: Decorator Design Pattern
W
at runtime
\} represents an object version of a linked list
U
where a client does not need to know about the
subclasses in the list
T
\} emphasizes the structural properties of the
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
W
Composite Design Pattern
TU
JN
Composite
Design Purpose
ld
Represent a Tree of Objects
or
Design Pattern Summary
W
Use a recursive form in which the
U
tree class aggregates and inherits
T
from the base class for the objects.
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
non-leaf node leaf node
or
W
Classes U Component 1..n
NonLeafNode
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Composite Class Model
Component 1..n
ld
Client add( Component ) doIt()
or
FOR ALL elements e in
component e.doIt()
W
LeafNode NonLeafNode
doIt() doIt() component
T U
JN
ld
:NonLeafNode :NonLeafNode
or
doIt()
doIt()
W
doIt()
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Employee Hierarchy
Pete
ld
:President
or
Able Becky
:Manager :Manager
W
Lonny
U Cal Tina Thelma
:Teller :Clerk :Teller :Teller
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
Design Goal At Work: Flexibility, Correctness
W
We need to add and remove employees at
runtime and execute operations on all of them.
U
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Composite Design Pattern
Bank/Teller Example
ld
Client Employee 1..n
stateName()
or
reports
W
Clerk Teller Supervisor
stateName() stateName() add(Employee)
T U
Setup
Manager President
JN
main()
stateName() stateName()
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
:President xxxx
*
:Employee
or
doClientTasks()
stateName()
W
stateName()
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Composite
in java.awt
ld
Component
1..n
or
Container
W
component
T
Window
U Canvas ..
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
Key Concept: Composite Design Pattern
W
-- used to represent trees of objects.
U
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
W
Adapter Design Pattern
TU
JN
Adapter
Design Purpose
ld
Allow an application to use external
or
functionality in a retargetable manner.
W
U Design Pattern Summary
Write the application against an abstract
T
version of the external class; introduce a
subclass that aggregates the external class.
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
Adapter Example
www.alljntuworld.in JNTU World
AbstractClass RequiredClass
ld
clientNameForRequiredMethod() requiredMethod()
or
Client adaptee
W
Adapter
clientNameForRequiredMethod()
U
{ adaptee. requiredMethod();}
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
:RequiredClass
or
clientNameForRequiredMethod()
RequiredMethod()
W
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
Design Goal At Work: Flexibility and Robustness
W
We want to separate the application as a whole from
financial calculations which will be performed externally.
U
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
Application Adaptation Legacy system
or
Financial
amount() Principle
computeValue()
W
FinancialAdapter
U
Client amount()
T
JN
Code Example
ld
class FinancialAdapter extends Financial
{
or
Principal legacyAdaptee = null;
W
float amount(float originalAmount, float numYears, float intRate)
{
return legacyAdaptee.computeValue(orginalAmount, numYears, intRate);
}
}
TU
executeFinanceApplication(new FinancialAdapter() );
JN
ld
or
Key Concept: Adapter Design Pattern
W
-- to interface flexibly with external functionality.
U
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
W
Flyweight Design Pattern
TU
JN
Flyweight
Design Purpose
ld
Manage a large number of almost
or
indistinguishable objects without
constructing them all at once.
W
Design Pattern Summary
U
Share representatives for the objects; use
T
context to obtain the effect of multiple instances.
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Flyweight
Class
Model
ld
Client
or
FlyweightFactory 1..n Flyweight
getFlyweight(Characteristic) doAction(Context)
W
static method
ConcreteFlyweight
doAction(Context)
U
Flyweight
T
singleton
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
:Flyweight
or
getFlyweight()
W
flyweight
Get context
....
U
doAction( context )
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
W
TU
JN
ld
or
W
TU
JN
ld
or
Design Goal At Work: Space Efficiency
W
We want to avoid proliferating an
object for every item to be displayed.
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
Key Concept: Flyweight Design Pattern
W
-- to obtain the benefits of a large set of
individual objects without efficiency penalties.
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
W
Proxy Design Pattern
TU
JN
Proxy
Design Purpose
ld
Avoid the unnecessary execution of expensive
or
functionality in a manner transparent to clients.
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Proxy Design
Pattern
Client
<<abstract>>
BaseActiveClass
ld
Instantiate with
Proxy object expensiveMethod()
anotherMethod()
or
W
RealActiveClass realActiveObject Proxy
expensiveMethod() expensiveMethod()
anotherMethod() anotherMethod()
TU
. . . // One way to check if it is really needed:
if ( realActiveObject == null ) // never referenced {
realActiveObject = getRealActiveObject();
JN
realActiveObject.expensiveMethod();
Adapted from Software Design: From }
Programming to Architecture by Eric J. Braude
(Wiley 2003), with permission. else // try to avoid calling the real expensiveMethod()
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
expensiveMethod()
W
( if needed: )
realExpensiveMethod()
T U
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
> all
or
I/O of Telephone
W
> middle
Record Proxy
Example
U
> all
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
Design Goal At Work: Efficiency and Reuse
W
Avoid unnecessary data downloads.
U
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
static showMiddleRecord()
or
RemoteTelNums 1
W
remoteTelNums TelNumsProxy
getTelNums() U getTelNums()
Setup
T
Ensures that . . . // One way to check if really needed:
if ( value == null ) // never referenced
JN
TelephoneApp makes
calls with remoteTelNums.getTelNums();
TelNumsProxy instance else // no need to call getTelNums()
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
Key Concept: Proxy Design Pattern
W
-- to call expensive or remote methods.
U
T
JN
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
Facade provides an interface to collections of objects
or
Decorator adds to objects at runtime (in a list structure)
Composite represents trees of objects
W
Adapter simplifies the use
of external functionality
U
Flyweight gains the advantages of using multiple
instances while minimizing space penalties
T
JN
ld
PATTERNS-I & II
Behavioral Patterns
or
Chain of Responsibility Visitor
Command
W
Interpreter
Iterator
\} Mediator
TU
\} Memento
\} Observer
JN
\} State
Strategy
Template Method
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
loose coupling)
(requests through a chain of (externalize and re-instantiate object state)
ld
candidates) (encapsulates a (defines and maintains dependencies)
request)
(change behaviour according to changed state)
or
(grammar as a class (encapsulates an algorithm in an object)
hierarchy) (abstracts
(step-by-step algorithm w/ inheritance)
traversal and access)
W
(encapsulated distributed behaviour)
(indirection for
11 - Behavioral CSC407 1
TU
JN
Observer
ld
Define a one-to-many dependency between objects so
that when one object changes state, all its dependents are
notified and updated automatically.
or
A common side-effect of partitioning a system into a collection of
cooperating classes is
the need to maintain consistency between related objects
W
You don't want to achieve consistency by making the classes
tightly coupled, because that reduces their reusability.
TU
a.k.a. Publish-Subscribe
Common related/special case use: MVC
Model-View-Controller pattern
JN
11 - Behavioral CSC407 2
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Motivation
ld
or
W
TU
Separate presentation aspects of the UI from the underlying
application data.
e.g., spreadsheet view and bar chart view don't know about each other
JN
11 - Behavioral CSC407 3
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Structure
ld
or
W Subject
TU
knows its observers
any number of Observers may observe one subject
Observer
defines an updating interface for objects that should be notified of
JN
11 - Behavioral CSC407 4
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Structure
ld
or
W
Concrete Subject
stores the state of interest to ConcreteObservers
TU
send notification when its state changes
Concrete Observer
maintains a reference to the ConcreteSubject objects
JN
Collaborations
ld
or
W
TU
subject notifies its observers whenever a change occurs that
would make its observers' state inconsistent with its own
After being informed, observer may query subject for changed info.
JN
11 - Behavioral CSC407 6
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Applicability
ld
When an abstraction has two aspects, one dependent
upon the other
e.g., view and model
or
Encapsulating these aspects into separate objects lets
you vary them independently.
W
when a change to one object requires changing others,
and you don't know ahead of time how many there are or
TU
their types
when an object should be able to notify others without making
assumptions about who these objects are,
you don't want these objects tightly coupled
JN
11 - Behavioral CSC407 7
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Consequences
ld
abstract coupling
no knowledge of the other class needed
supports broadcast communications
or
subject doesnt care how many observers there are
spurious updates a problem
W
can be costly
unexpected interactions can be hard to track down
problem aggravated when simple protocol that does not say what
TU
was changed is used
JN
11 - Behavioral CSC407 8
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Implementation
Mapping subjects to observers
ld
table-based or subject-oriented
Observing more than one subject
or
interface must tell you which subject
data structure implications (e.g., linked list)
W
Who triggers the notify()
subject state changing methods
> 1 update for a complex change
TU
clients
complicates API & error-prone
can group operations and send only one update
transaction-oriented API to client
JN
11 - Behavioral CSC407 9
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Implementation
dangling references to deleted subjects
ld
send 'delete message'
complex code
or
must ensure subject state is self-consistent before sending
update
push versus pull
W
push: subject sends info it thinks observer wants
pull: observer requests info when it needs it
registration: register for what you want
TU
when observer signs up, states what interested in
ChangeManager
if observing more than one subject to avoid spurious updates
Can combine subject and observer
JN
11 - Behavioral CSC407 10
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Chain Of Responsibility
ld
Avoid coupling the sender of a request to its receiver by
giving more than one object a chance to handle the request.
Chain the receiving objects and pass the request along the chain
or
until an object handles it.
W
TU
JN
11 - Behavioral CSC407 11
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Motivation
ld
or
W
TU
Context-sensitive help
User can obtain information on any part of a UI by clicking on it.
If no help available (e.g., for a button), system should display a more
JN
general help message about the context (e..g, the dialog box containing the
button).
11 - Behavioral CSC407 12
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Motivation
ld
or
W
Objects forward the request
TU
until there is one that can
handle it.
The key is that the client
does not know the object that
JN
11 - Behavioral CSC407 13
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Applicability
ld
More than one object may handle a request, and
the handler isn't known a priori.
or
The handler should be ascertained automatically.
W
without specifying the receiver explicitly.
TU
The set of objects that can handle a request should
be specified dynamically.
JN
11 - Behavioral CSC407 14
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Structure
ld
or
W
TU
JN
11 - Behavioral CSC407 15
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Structure
ld
or
W
Handler
defines an interface for handling requests
implements the successor list (optional)
TU
ConcreteHandler
handles requests for which it is responsible
can access its successor
forward to successor if it can't handle the request
JN
Client
initiates the request to the first ConcreteHandler in the chain.
11 - Behavioral CSC407 16
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Consequences
ld
reduced coupling
receiver and sender have no explicit knowledge of each other
can simplify object interactions
or
added flexibility
can add or change responsibilities by changing the chain at run-
W
time.
receipt is not guaranteed.
request may fall off the end of the chain
TU
JN
11 - Behavioral CSC407 17
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
State
ld
Allow an object to alter its behavior when
or
its internal state changes.
The object will appear to change its class.
W
TU
JN
11 - Behavioral CSC407 18
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Motivation
ld
or
W
TU
A TCPConnection object that responds differently to
requests given its current state.
JN
Applicability
ld
An object's behavior depends on its state, and it must
change its behavior at run-time depending on that state.
Operations have large, multipart conditional
or
statements that depend on the object's state.
This state is usually represented by one or more enumerated
W
constants.
Often, several operations will contain this same conditional
structure.
The State pattern puts each branch of the conditional in a separate
TU
class.
This lets you treat the object's state as an object in its own right
that can vary independently from other objects.
JN
11 - Behavioral CSC407 20
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Structure
ld
or
W
Context
defines the interface of interest to clients.
maintains an instance of a ConcreteState subclass that defines the current
TU
state.
State
defines an interface for encapsulating the behavior associated with a
particular state of the Context.
ConcreteState subclasses
JN
Consequences
ld
It localizes state-specific behavior and partitions
behavior for different states.
The State pattern puts all behavior associated with a particular
or
state into one object.
Because all state-specific code lives in a State subclass, new states
and transitions can be added easily by defining new subclasses.
W
It makes state transitions more explicit
State is represented by the object pointed to.
It protects the object from state-related inconsistencies.
All implications of state changed wrapped in the atomic change of
TU
1 pointer.
State object can be shared
if no data members they can be re-used across all instances of the
JN
Context
11 - Behavioral CSC407 22
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Mediator
ld
Defines an object that encapsulates how a set of objects
interact.
promotes loose coupling by keeping objects from referring to each
or
other explicitly
lets you vary their interaction independently
W
TU
JN
11 - Behavioral CSC407 23
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Motivation
ld
or
W
TU
A collection of widgets that interact with one another.
JN
11 - Behavioral CSC407 24
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Motivation
ld
or
W
TU
Create a mediator to control and coordinate the
interactions of a group of objects.
JN
11 - Behavioral CSC407 25
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Motivation
ld
or
W
TU
e.g.,
list box selection moving to entry field
entryField now calls WidgetChanged() and enables/disables
JN
entry field does not need to know about list box and vice-versa
11 - Behavioral CSC407 26
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Motivation
ld
or
W
TU
JN
11 - Behavioral CSC407 27
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Applicability
ld
A set of objects communicate in a well-defined
but complex manner
or
reusing an object is difficult because it refers to
and communicates with many other objects
W
a behavior that's distributed between several classes
should be customizable without a lot of subclassing
TU
JN
11 - Behavioral CSC407 28
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Structure
ld
or
W
TU
JN
11 - Behavioral CSC407 29
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Structure
ld
or
W
Mediator
defines an interface for communicating with Colleague objects
ConcreteMediator
knows and maintains its colleagues
TU
implements cooperative behavior by coordinating Colleagues
Colleague classes
each Colleague class knows its Mediator object
each colleague communicates with its mediator whenever it would have
JN
11 - Behavioral CSC407 30
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Conseq
ld
uences
limits subclassing
or
localizes behaviour that
otherwise would need to be
modified by subclassing the
W
colleagues
decouples colleagues
can vary and reuse colleague
and mediator classes
TU
independently
simplifies object protocols
replaces many-to-many
JN
ld
abstracts how objects
cooperate
or
can focus on object interaction
apart from an objects
individual behaviour
W
centralizes control
mediator can become a
monster
TU
JN
UNIT-VIII
ld
WHAT TO EXPECT FROM DESIGN
PATTERNS
or
Adapter Pattern
W
TU
JN
ld
What is Adapter?
or
Intent
Change the interface of a class into another
interface which is expected by the client.
Also Known as
W
Wrapper
TU
- Total 17 pages - 1
JN
ld
or
Example :- Drawing editor -lets users draw and arrange graphical elements (lines, polygons, text,
etc.) into pictures and diagrams.
W
A TextShape subclass that can display and edit text is considerably more difficult to implement,
since even basic text editing involves complicated screen update and buffer management.
Meanwhile, an off-the-shelf user interface toolkit might already provide a sophisticated TextView class
TU
for displaying and editing text. Ideally we'd like to reuse TextView to implement TextShape, but the
toolkit wasn't designed with Shape classes in mind. So we can't use TextView and Shape objects
interchangeably.
- Total 17 pages - 1
JN
ld
Motivation example
or
W
TU
JN
- Total 17 pages - 1
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
or
Solution
TextShape should adapt the TextView interface to Shapes.
This can be achieved in two ways
W
1) By inheriting Shapes interface and TextViews implementation
- Total 17 pages - 1
ld
Applicability
or
2. Use an existing class whose interface does not match the requirement
3. Create a reusable class though the interfaces are not necessary compatible
with callers
W
TU
- Total 17 pages - 1
JN
ld
Structure (Class)
or
A class adapter uses multiple inheritance to adapt one interface to another:
W
TU
JN
- Total 17 pages - 1
ld
Structure (Object)
or
W
TU
JN
- Total 17 pages - 1
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
Participants
Target(Shape)
Defines the domain-specific interface that client uses
or
// Client (DrawingEditor)
Collaborates with objects conforming to the Target interface
W
// Adaptee (TextView)
Defines an existing interface that needs adapting
// Adapter (TextShape)
Adapts the interface of Adaptee to the Targer
TU
interface
- Total 17 pages - 1
JN
ld
Collaborations
or
Clients call operations on an Adapter instance. In turn, the adapter calls Adaptee
operations that carry out the request.
W
TU
- Total 17 pages - 1
JN
ld
Class Adapter Pattern
Consequences
or
Adapts Adaptee to Target by committing to a concrete Adapter class
Lets adapter override some of Adaptees behaviour
Introduces only one object, and no additional pointer indirection is needed
W
to get to the adaptee
TU
- Total 17 pages - 1
JN
ld
Object Adapter Pattern
Consequences
or
Lets a single Adapter work with many Adaptees (i.e., adaptee
and all its subclass)
Makes it harder to override adaptee behaviour
W
TU
- Total 17 pages - 1
JN
ld
Consequences cont..
or
other issues to consider when using the Adapter pattern:
W
Pluggable adapters
ld
Implementation
Implementing class adapters in C++
or
Pluggable adapters
\endash Using abstract operations
\endash Using delegate objects
W
\endash Parameterized adapters
TU
JN
ld
Known uses
ET++Draw
or
ObjectWorks / smalltalk
W
TU
JN
- Total 17 pages - 1
ld
Related Patterns
or
Decorator enhances another object without changing its interface.
W
TU
- Total 17 pages - 1
JN
ld
Conclusions
or
Allows collaboration between classes with incompatible interfaces
W
Useful pattern which promotes reuse and allows integration of diverse software
components
- Total 17 pages - 1
TU
JN
ld
Motivation
Problem
or
How can unrelated classes like TextView work in an application that expects classes
with a different and incompatible interface
W
TU
JN
- Total 17 pages - 1
ld
Pluggable Adapters
or
W
TU
JN
- Total 17 pages - 1
ld
Two-way Adapters
or
class SquarePeg { class PegAdapter: public SquarePeg,
public: RoundPeg {
void virtual squarePegOperation() { public:
blah }
W
} void virtual roundPegOperation() {
squarePegOperation();
class RoundPeg {
TU
}
public:
void virtual squarePegOperation() {
void virtual roundPegOperation() { blah
} add some corners;
JN
} roundPegOperation();
ld
15.Additional Topics
or
W
TU
JN
Bridge Pattern
ld
Intent
Decouple an abstraction from its implementation so that the
or
two can vary independently
Also Known As
W
TU Handle / Body
JN
Motivation
1. It's inconvenient to extend the Window abstraction to
ld
cover different kinds
of windows or new platforms
or
2. It makes client code platform-dependent.
SOLUTION
Clients should be able to create a window without
W
committing to a concrete implSementation.
TU
JN
ld
The Bridge pattern addresses these problems by putting the
Window abstraction and its implementation in separate class
or
hierarchies.
W
There is one class hierarchy for window interfaces (Window,
IconWindow, TransientWindow) and a separate hierarchy for
platform-specific window implementations, with WindowImp
as its root
TU
JN
ld
or
W
TU
JN
Applicability
ld
You Want to avoid a permanent binding between an
abstraction and implementation.
or
When abstractions and implementations should be
extensible through subclassing.
3) 3) you want to hide the implementation of an abstraction
W
completely from clients
TU
JN
Structure
ld
Client
or
Implementer
Abstraction
W
OperationImp
()
TU
RefinedAbstract ConcreteImplement ConcreteImplement
JN
ld
or
W
TU
JN
Participants
Abstraction (window):
ld
- define the abstractions interface
- maintains a reference to an object of type Implementor
or
Refined Abstraction (iconwindow):
- extends the interface defined by Abstraction
W
Implementor (WindowImp):
- defines an interface for implementation classes.
CONCREteImplementor ( XWindowImp, PMWindowImp):
TU
- implements the Implementors interface and defines its concrete
implementation.
JN
Collaborations
ld
Abstraction forwards client requests to its Implementor
object.
or
Consequences
Decoupling interface and implementation
\endash Improved extensibility
W
3.Hiding implementation details from clients
TU
JN
Implementation
ld
1) Only one Implementor
or
2. Creating the right Implementor
W
TU
JN
UNIT-1
1. Discuss about implementation issues in builder design pattern.
2. Explain sample code of builder design pattern.
ld
3. Explain the features of structural patterns in detail.
5. Explain the motivation of adapter design pattern.
or
5. State the differences between Traversal and Traversal actions.
6.Explain visitor class and subclasses in detail.
W
7.Explain with a neat diagram the Design Pattern relationships.
10. Explain the class design structure of an editor for music scores with
suitable design pattern.
12. Explain the structure & participants of chain of Responsibility with one
example.
13. Explain the motivation for known Facade method with relevant Patterns.
15. What is the intent uses & related pattern of Decorator Method?
302
ld
17.Give the Catalog for DP
or
19.Explain the Abstract Factory design pattern in detail.
UNIT-III
W
20.What is the intent on Write a detailed code on Builder design pattern?
23.Give the indent and code on the Chain of Responsibility design pattern.
303
UNIT-IV
31. Which pattern separates user interface from functional core?
32. Compare and contrast architectural patterns, design patterns
ld
33. Briefly discuss a step-by-step approach how to use a design pattern
35. Illustrate the relationship between the different types of design patterns
35. A patient is suffering from Headache for some time and hence forth
or
hospital where he stated the same to the receptionist.
36. Briefly discuss applicability of faade structural patterns.
37. Discuss the application of visitor class and visitor pattern
38.Compare and contrast Mediator, Strategy and Observer design patterns.
W
39. Discuss the case study of A-7E in utilizing architectural structures.
UNIT-V
TU
45. Explain the product lines architecture and discuss the reasons that makes
45. Discuss the motivation, applicability, participants, collaborations,
46. Draw the structure and also discuss the motivation, applicability,
47. Discuss the motivation, applicability, participants, collaborations,
48. Draw the structure and also discuss the motivation, applicability,
49. Describe the three views of Celsius Tech architecture case study.
304
sample code.
UNIT-VI
ld
52.Explain about a Target Refactoring approach method.
53. Discuss about implementation issues in builder design pattern.
55. Explain sample code of builder design pattern.
or
55. What are the implementation considerations of Momento pattern?
56.Discuss the Applicability of Observer pattern.
57. Discuss about embellishing the user interaface in detail.
58.Explain about supporting multiple window systems in designing a
W
document Editor.
59.Differentiate between adapter and bridge design pattern.
60. What are the known uses of adapter structural pattern? Explain.
TU
UNIT-VII
JN
UNIT-VIII
ld
70.Explain how to select a Design Pattern.
71.How can we relate RunTime and Compile Time structures? Explain.
72.Explain the implementation issues of Visitor pattern with sample
or
code.
73.Explain the following:
(a) A target refactoring
(b) Patterns in software.
W
75.Mention the uses & related patterns of bridge design pattern.
75.Mention the participants of bridge pattern and explain the functions
of each.
TU
UNIT-1II
6. a) Briefly discuss a step-by-step approach how to use a design pattern
b) Illustrate the relationship between the different types of design patterns
7. a) A patient is suffering from Headache for some time and hence forth
ld
hospital where he stated the same to the receptionist.
b) Briefly discuss applicability of faade structural patterns.
8. a) Discuss the application of visitor class and visitor pattern
b) Compare and contrast Mediator, Strategy and Observer design patterns.
or
UNIT-1V
9. Discuss the case study of A-7E in utilizing architectural structures.
10.a) Discuss about implementation issues in builder design pattern.
W
(b) Explain sample code of builder design pattern.
11. (a) Explain the features of structural patterns in detail.
(b) Explain the motivation of adapter design pattern
UNIT-V
12 (a) State the di erences between Traversal and Traversal actions.
TU
15Explain the class design structure of an editor for music scores with suitable
design pattern
UNIT-VI.
16(a) Explain the motivation of Iterator pattern.
(b) Explain the structure & participants of chain of Responsibility with one
example.
307
17(a) Explain the motivation for known Facade method with relevant Patterns.
(b) What is the intent uses & related pattern of Decorator Method?
UNIT-VII
18. what are the uses of abstract factory design pattern ? Explain
19. write a detailed note on prototype design pattern
ld
20. Explain how to select a design pattern
21. How can we relate run time and compile time structures. Explain
UNIT-VIII
22. Write about (a)delegation (b) A common design vocabulary (c) The Object
or
Community
23. Explain the collaboration of bridge pattern.
24. Write a short note on a implementation issues of composite pattern.
W
19.Unit-wise Quiz Questions And Long Answer Questions
QUIZ QUESTIONS
TU
UNIT-1
Functional decomposition is the approach to analysis that breaks down (decomposes) a problem
into its functional parts without too much concern for global requirements and future
modifications. (p. 5)
JN
The user's understanding of what they need and what is possible grows and changes as they
discuss the problem with analysts. The developer's understanding of what is possible and what is
needed evolves as they become familiar with the domain and with the software. The technical
environment evolves, forcing changes in how to implement. (p. 6)
3. I advocate thinking about responsibilities rather than functions. What is meant by this?
Give an example.
308
Rather than thinking first about how something is done (functions), the analyst should focus on
what the routine is responsible for doing - how it does it does not matter. The control program is
much simpler in this case. (p. 12).
Cohesion is how strongly the internal operations of a routine are related to each other. Coupling
is how strongly a routine is dependent upon other routines. (p. 8)
ld
5. What is the purpose of an "interface" to an object?
It provides the methods whereby other objects can tell the object what to do. (p. 16)
or
A specific, unique occurrence of a more abstract object. An object is an instance of a class. (p.
17)
At the conceptual level, an abstract class is a placeholder for a set of classes. It gives a way to
assign a name or label to a set of classes. At the specification level, an abstract class is a class
TU
9. What are the three main types of accessibility that objects can have?
Any kind of hiding. Both data and behavior may be encapsulated. (p. 21)
JN
Conceptual: the high-level concepts in a system (concepts, not software). At the conceptual
level, an object is a set of responsibilities.
309
Specification: the interfaces between things in the software (software, not code). At the
specification level, an object is a set of methods.
Implementation: how an individual routine works (code). At the implementation level, an object
is code and data. (p. 13, 15-16)
UNIT-1I Interpretations
13. Sometimes, programmers use "modules" to isolate portions of code. Is this an effective
ld
way to deal with changes in requirements? Why or why not?
Changes to one function or routine can have impacts on other routines. Usually, routines are not
independent (p. 10).
or
15. It is too limited to define an abstract class as a class that does not get instantiated. Why
is this definition too limited? What is a better (or at least alternative) way to think about
abstract classes?
It is too limited because it only talks in terms of its implementation: what the abstract class does
and how it is treated as software. It does not describe why I would want to use an abstract class:
the motivation for it and how to think about it. It ignores the "conceptual perspective" of objects
W
that analysts need to keep in mind as they work with users to understand problems. At the
conceptual level, an abstract class is a placeholder for a set of classes. It gives a way to assign a
name or label to a set of classes so that I can interact with them as a whole without getting
trapped by the details. (p. 19)
15. How does encapsulation of behavior help to limit the impact of changes in
requirements? How does it save programmers from unintended side effects?
TU
It makes the control program much less complicated since it does not have to be responsible for
as much. It limits the impact that changes to the internals of an object can have on the rest of the
application. (p. 25)
16. How do interfaces help to protect objects from changes that are made to other objects?
Interfaces define the only ways that those external objects can communicate with the object. It
JN
protects me from side effects because I know what is coming into the system.
17. A classroom is used to describe objects in a system. Describe this classroom from the
conceptual perspective.
The classroom contains students who are responsible for their own behaviors: how to move from
here to there, how to go from class to class. It contains a teacher who tells students where to go.
310
ld
1. What is the difference between an "is-a" relationship and a "has-a" relationship? What
are the two types of "association" relationships?
"is-a" indicates that one object is a "kind of" a class; for example, a "sail boat" is a kind of "boat"
which is a kind of "type of transportation".
or
"has-a" indicates that one class "contains" another class; for example, a car has wheels.
There are two types of "associations": containment (has-a) and "uses" (p. 29)
2. In the Class diagram, a class is shown as a box, which can have up to three parts.
W Describe these three parts.
The top box is the name (label) of the class. This is required.
The middle box, if it is shown, shows the data members of the class.
The bottom box, if it is shown, shows the methods (functions) of the class. (p. 32)
TU
3. Define cardinality.
Cardinality indicates the number of things that another object can have (p. 36)
The Sequence diagram is one type of Interaction Diagram in the UML. It shows how objects
interact with other objects. (p. 38)
JN
Interpretations
1. Give an example of an "is-a" relationship and the two "association" relationships. Using
these examples,
311
2. Figure 2-8 shows a Sequence diagram. How many steps are shown in the figure? How
many objects are shown and what are they?
ld
There are 13 steps in the diagram
There are 6 objects shown: Main, ShapeDB, Collection, shape1:Square, shape2:Circle, and
Display. (p. 39)
3. When objects communicate with each other, why is it more appropriate to talk about
or
"sending a message" than "invoking an operation"?
When objects "talk" to each other, it is called "sending a message." You are sending a request to
another object to do something rather than telling the other object what to do. You allow the
other object to be responsible enough to figure out what to do. Transferring responsibility is a
fundamental principle of object-oriented programming. It is quite different from procedural
W
programming where you retain control of what to do next, and thus might "calling a method" or
"invoke an operation" in another object.
top
Observations
1. What five features in sheet metal will this system have to address?
The features are Slot, Hole, Cutout, Special, and Irregular (p. 57)
The V1 system has a collection of subroutine libraries that interacts with the CAD/CAM model.
To get information about the CAD/CAM model, you have to make a series of calls (p. 53)
312
The V2 system is an object-oriented system. The geometry is stored in objects, each of which
represents a feature. To get information about a feature, you interrogate the object for that
feature. (p. 55)
We have different types of CAD/CAM systems. A third system (the "expert system") has to
ld
extract information from whichever CAD/CAM system in order to work with the geometry. The
two CAD/CAM systems are implemented in completely different ways and require completely
different ways of interacting with them, even though they contain essentially the same
information (p. 55)
2. Why is polymorphism needed at the geometry-extractor level but not at the feature
or
level?
Polymorphism is required at the geometry extractor level because the "expert system" needs to
know what type of features it is dealing with: slot, hole, etc. It is insufficient for the expert
system simply to work on generic "features." Polymorphism does not buy me anything at the
feature level. The expert system does not need to care about the particular method that is used to
W
extract that feature. While we could hard-code the extraction method into the expert system, that
would be bad if we ended up getting a new CAD/CAM system that uses yet another method of
working with geometry. Polymorphism frees us from having to worry about the particular
extraction method: the expert system can simply use a generic "geometry extractor" that worries
about extractions. (p. 52)
What is the most effective method you have found for recording user terminology?
top
313
Observations
Abstract class
Cardinality
ld
Derivation
Composition
or
Public methods
They need the ability to plug-and-play different CAD/CAM systems without changing the expert
system (p. 63)
It has low cohesion: core functions are scattered amongst many classes. (p. 63)
Interpretations
1. Describe the first approach to solving the CAD/CAM problem. Was it a reasonable first
approach?
314
The first object-oriented approach to a solution is to specialize a feature for each case: a Slot
class for V1 and a Slot class for V2. Each V1 type case communicates with the V1 libraries and
V2 type case communicates with V2 libraries. It is a reasonable approach to begin with (p. 59). It
gives insights into the problem. But it should not be implemented!
1. "Delay as long as possible before committing to the details." Do you agree? Why or why
not?
ld
2. One solution was rejected because "intuition told me it was not a good solution." Is it
appropriate for analysts / programmers to be guided by their instincts?
top
or
UNIT-1VAn Introduction to Design Patterns
Observations
W
1. Who is credited with the idea for design patterns?
The architect, Christopher Alexander developed design patterns in the late 1970s. The "Gang of
Four" took this idea in the 1990s and applied them to software design. I point out that one school
of anthropology used patterns to study cultures in the 1950s. (p. 72). Also, the ESPRIT
consortium used patterns for understanding human thought patterns in ways that could be
implemented in computer programs in the 1980s (p. 77)
TU
2. Alexander discovered that by looking at structures that solve similar problems, he could
discern what? Designs / solutions that are high quality. And that this was objectively
measurable (p. 73)
3. Define pattern. A pattern is a solution to a problem that occurs in a given context. (p. 75)
315
GoF Reference: where to look in the Gang of Four book for more information. (p. 79)
Patterns give you perspective on the problem, freeing you from committing to a solution too
ld
early. (p. 80)
6. The Gang of Four suggests a few strategies for creating good object-oriented designs.
What are they?
Design to interfaces
or
Favor aggregation over inheritance Find what varies and encapsulate it (p. 85)
Interpretations
1. "Familiarity sometimes keeps us from seeing the obvious." In what ways can patterns
W
help avoid this? We can gain insights from previous solutions, have our attention drawn to
features of the problem that I might not otherwise think of (until too late) (p. 80)
2. The Gang of Four cataloged 23 patterns. Where did these patterns come from? It came
from their insights into solutions that had already been developed within the software
community. (p. 78)
TU
5. What do you think "find what varies and encapsulate it" means? Look for what is
changing and make a more generic version of it so that you can see what is truly going on in your
system and not get caught up in the details. (p. 78)
5. Why is it desirable to avoid large inheritance hierarchies? They are very complex to
JN
1. Think of a building or structure that felt particularly "dead". What does it not have in
common with similar structures that seem to be more "alive"?
2. "The real power of patterns is the ability to raise your level of thinking." Have you had
an experience in which this was true? Give an example.
316
top
Observations
ld
1. Define Faade.
A Faade is "The face of a building, especially the principal face" - dictionary.com. It is the front
that separates the street from the inside.
or
2. What is the intent of the Faade pattern?
Clients work with sub-systems through the Faade's interfaces. They do not interact with the
underlying methods directly (p. 91)
5. Does the Faade pattern usually give you access to the entire system?
Not usually. In general, Faade give access to a portion of the system, one that is customized to
our needs. (p. 89)
JN
Interpretations
1. The Gang of Four says that the intent of the Faade pattern is to "provide a unified
interface to a set of interfaces in a sub-system. Faade defines a higher-level interface that
makes the subsystem easier to use." What does this mean? Give an example.
The Faade gives a simpler way to access an existing system by giving an interface that is
customized to the needs you have. (p. 90)
Example is a class that insulates a client program from a database system (p. 92)
317
2. Here is an example of a Facade that comes from outside of software. Pumps at gasoline
stations in the US can be very complex. There are many options on them: how to pay, the
type of gas to use, watch an advertisement. One way to get a unified interface to the gas
pump is to use a human gas attendant. Some states even require this.
ld
Opinions and Applications
1. If you need to add functionality beyond what the system provides, can you still use the
Faade pattern?
2. What is a reason for encapsulating an entire system using the Faade pattern?
or
3. Is there a case for writing a new system rather than encapsulating the old system with
Faade? What is it?
5. Why do you think the Gang of Four call this pattern "Faade"? Is it an appropriate
name for what it is doing? Why or why not?
W
top
Observations
1. Define Adapter.
"Adapter" is something that allows one thing to modify itself to conform to the needs of another
thing.
The intent of the Adapter is to match an existing object that is beyond your control to a particular
interface. (p. 102)
A consequence is that the pattern allows for preexisting objects to fit into new class structures
without being limited by their interfaces (p. 102). The example in the book is the drawing
program that wants to use an existing Circle object but the existing object doesn't provide exactly
318
the same methods as the rest of the system. The Adapter provides a translation to these methods.
(p. 101)
5. Which object-oriented concept is being used to define the relationship between Shape
and Points, Lines, and Squares?
ld
To allow for continued use of polymorphism. It is often used in conjunction with other design
patterns. (p. 101)
6. What does the Adapter pattern free you from worrying about?
or
Adapter frees me from worrying about the interfaces of existing classes when doing a design. If
the class doesn't do what I need, I can create an Adapter to give it the correct interface. (p. 103)
Interpretations
1. The Gang of Four says that the intent of the Adapter pattern is to "convert the interface
of a class into another interface that the clients expect. Adapter lets classes work together
TU
It means that I have a class that needs to interact with another class through a certain set of
method calls. If the interface of that other class does not provide these method calls, the Adapter
sets up a new interface to do the translation. (p. 103) An example would be a reporting
application that needs pulls data from two different database systems. My application wants to
JN
use a "GetDate" method to pull information from the database, but the database systems don't
provide that through their API. I write an Adapter that provides the GetDate method in its
interface and is responsible for pulling the data appropriately.
2. "The Circle object wraps the XXCircle object." What does this mean?
Circle completely insulates XXCircle from the system. Circle manifests the entire behavior of
XXCircle to the system, although with a different interface / way of accessing XXCircle. (p. 100)
319
3. The Faade pattern and the Adapter pattern may seem similar. What is the essential
difference between the two?
In both cases, there is a preexisting class or classes that have functionality I need. In both cases, I
create an intermediary object with interfaces that my system wants to use and that has
responsibility for mapping that to the preexisting class. Both Faade and Adapter are wrappers.
The Adapter is used when the client already has predefined interfaces that it expects to use and
when I need to use polymorphism.
ld
The Faade is used when I need a simpler interface to the existing object. (p. 105)
or
equivalent" representations from one language to the other so that the concepts are
communicated in the way that the recipient expects and needs to hear it.
Another example could be a travel agent, seen as the common interface between a passenger
W
making arrangements and an airline with its own systems. Each has competing systems, speaking
different languages
1. When is it more appropriate to use the Faade pattern rather than the Adapter pattern?
How about the Adapter pattern instead of Faade pattern?
TU
2. Why do you think the Gang of Four call this pattern Adapter? Is it an appropriate name
for what it is doing? Why or why not?
top
Observations
Encapsulation is best thought of as "any kind of hiding." This can mean hiding data, or behavior,
or implementations, or derived classes, or any other thing. (p. 113)
320
2. What are the three perspectives for looking at a problem? (You may need to review
Chapter 1, "The Object-Oriented Paradigm").
The three perspectives are the Conceptual perspective, the Specification perspective, and the
Implementation perspective.
Interpretations
1. There are two mention different ways to understand objects: "data with methods" and
ld
"things with responsibilities."
The second approach takes looks at what an object is supposed to do, what its essential concepts
or
are, without worrying about how to do them. It fights against the tendency of programmers to
want to jump to coding too soon. (p. 110-111).
By focusing on what an object is supposed to do rather than how it does it, I can be more flexible
in design. It helps to think about the public interfaces that will be required and what those
interfaces need to do. (p. 111).
W
2. Can an object contain another object? Is this different than one object containing a data
member?
In object-oriented systems, everything is an object. An object can contain another object, data, or
anything. In fact, data types are also objects, so there is no difference. (p. 118)
TU
3. What is meant by the phrase find what varies and encapsulate it? Give an example
Variation represents special cases that complicate understanding. At the conceptual level, find a
common label to a set of these variations. Variation can be in data, in behavior (p. 116)
By looking at what objects must do (the Conceptual perspective), we determine how to call them
JN
(the Specification perspective). (p. 119). Commonality / Variability analysis reveals the
interfaces I need to handle all of the cases of the concept. (p. 121)
Specifications become abstract classes at the implementation level (p. 120). Given a
specification, the Implementation perspective shows how each of its variations must handled. (p.
121).
5. An abstract class maps to the "central binding concept." What does this mean?
321
The core concept is what defines what is common across a set of things that vary. An abstract
class represents this core concept. The name you give to that core concept Is the name for the
abstract class. (p. 120)
6. "Variability analysis reveals how family members vary. Variability only makes sense
within a given commonality."
ld
What types of objects are used to represent the variations?
Variability analysis looks for all of the variants of a concept: all of the concrete instances of an
abstract class. The "commonality" labels the essential concept that ties the variations together.
The goal is to find the best unifying name for the set of variations so that you can have a handle
to work with them as a set: to work with the forest instead of the trees.
or
Abstract classes are used to represent the common concept. Concrete instances are used to
represent the variations. (p. 139)
2. Preconceived notions limit one's ability to understand concepts. This was shown to be the
case with encapsulation. Can you think of a situation in which your preconceived notions
got in the way of understanding requirements? What happened and how did you overcome
it?
TU
3. The term inheritance is used both when a class derives from an nonabstract class to
make a specialized version of it and when an abstract class is used as a starting point for
different implementations. Would it be better if we had two different terms for these
concepts instead of using the same term?
5. How might you use commonality/variability analysis to help you think about ways to
modify a system?
JN
322
7. This chapter tried to present a new perspective on objects? Did it succeed? Why or why
not?
top
ld
Observations
or
Switches or ifs on a variable specifying the case we have Using function pointers or delegates (a
different one representing each case) Inheritance (make a derived class that does it the new way)
Design patterns
2. What are the three fundamental principles proposed by the Gang of Four that guide how
to anticipate change?
W
"Program to an interface, not an implementation." 1
"Favor object aggregation over class inheritance." 2 "Consider what should be variable in your
design.
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy
lets the algorithm vary independently from the clients that use it
Switches and/or conditionals can be eliminated. You must invoke all algorithms in the same way
(they must all have the same interface).
Interpretations
1. The Gang of Four suggests "considering what should be variable in your design." How is
this different from focusing on the cause of redesign?
323
The focus is on seeing where change might occur and then encapsulating it so that your system
will not be affected by change when it occurs. It assumes you will not be able to anticipate what
will change.
ld
The flow of the switches themselves becomes confusing. Hard to read. Hard to decipher. When a
new case comes in, the programmer must find every place it can be involved (often finding all
but one of them). I like to call this "switch creep".
5. What are the advantages of the design patterns approach to handing variation?
or
Improves cohesion
But this simplifies the bigger, more complicated program. Second, by doing this, I have made
inheritance better. When I need to use inheritance, there is now only one piece of functionality
changing within any one class. The bottomline is, the approach espoused by patterns will scale
while the original use of inheritance will not.
TU
1. Have you ever been in a situation where you did not feel you could afford to anticipate
change? What drove you that way? What was the result?
top
JN
Observations
324
Decouple means to separate or detach one thing from another. In our context, it means to have
one thing behave independently from another (or at least to state explicitly what that relationship
is)
Abstraction means to generalize or conceptualize: to step back from the more concrete to the
more conceptual or abstract. (p. 125)
ld
Implementation refers to the objects that the abstract class and its derivations use to put
themselves into operation or into service. (p. 125)
or
Boxes. These are shown at the top and represent the objects that are interacting.
Name in the form objectname:classname. The object name is optional.
Dashed vertical lines, also known as swim lanes, one for each object, to indicate time.
Arrows, may be horizontal or vertical, showing the interaction between objects. Each
arrow is labeled to describe the interaction
W Notes. This is optional. (p. 131)
5. What is Alexander's view of how to use patterns? Does he advocate starting with the
solution first or the problem to be solved first?
Alexander says that a pattern describes a problem which occurs over and over again in the
environment and then describes the core of the solution to that problem. This means that it is
TU
most important to understand the problem first and then tackle the solution. It is a mistake to try
finding the solution first. (p. 137)
5. What does commonality analysis seek to identify? What does variability analysis seek to
identify?
Commonality analysis focuses on finding structures that will not change over time while
variability analysis looks for structures that are likely to change. (p. 139)
JN
The derivations of an abstract class must use multiple implementations without causing an
explosion in the number of classes (p. 151).
"one rule, one place" says you should implement a rule in only one place. (p. 155). Note that this
results in a greater number of smaller methods.
325
Decoupling of the implementations from the objects that use them increases extensibility. Client
objects are freed from being aware of implementation issues. (p. 151)
Interpretations
1. The Gang of Four says that the intent of the Bridge pattern is to "decouple an
abstraction from its implementation so that the two can vary independently." What does
ld
this mean? Give an example.
What it means is that you can have an abstraction that is independent of its implementations. (p.
150) An example is a shape object that is responsible for knowing shapes and a Drawing class
that is responsible implementing drawing routines. Individual shapes don't have to know how to
do drawings (p. 156)
or
2. Why can tight coupling lead to an explosion in the number of classes?
Tight coupling means that as you get more variations in implementation, each class has to be
responsible for its own implementation.
W Opinions and Applications
1. "Look at objects in terms of their responsibilities rather than their behaviors." How does
this affect your view of the use of inheritance in an object-oriented system?
2. Why do you think the Gang of Four call this pattern "Bridge"? Is it an appropriate
name for what it is doing? Why or why not?
TU
top
Observations
JN
1. While using "switches" can be a reasonable solution to a problem that requires choosing
among alternatives, it caused problems for the driver problem discussed in this chapter.
What were these problems? What might a switch indicate the need for? The rules for
determining which driver to use are intermixed with the actual use of the drivers. This creates
both tight coupling and strong cohesion. (p. 165)
326
At first glance, you might be tempted to conclude it is because the factory is implemented as an
abstract class with a derivation for each case. But that is not the case. This pattern is called the
"Abstract Factory" because the things it is intended to build are themselves defined by
abstractions. How you choose to implement the factory variations is not specific to the pattern.
ld
Favor aggregation over inheritance
5. In this pattern, there are two kinds of factories. What does the "Abstract Factory" class
do? What do the "concrete factory" classes do?
or
The "Abstract Factory" class specifies which objects can be instantiated by defining a method for
each type of object.
The "concrete factory" classes specify which objects are to be instantiated. (p. 175)
W
5. What are the consequences of the Abstract Factory pattern?
The Abstract Factory isolates the rules about which objects to use from the logic about how to
use these objects. (p. 176)
Interpretations
TU
1. The Gang of Four says that the intent of the Abstract Factory pattern is to "provide an
interface for creating families of related or dependent objects without specifying their
concrete classes." What does this mean? Give an example.
It means that I need to coordinate the instantiation of several objects, a family of objects.
However, I want to insulate my system from having to know specifics of the particular concrete
object being instantiated. That is, the selection of which particular concrete instance to use might
depend upon another factor. An example would be a system that wants to manage records in a
database but be insulated from the specifics of which DBMS is being used. (p. 163)
JN
1. Why do you think the Gang of Four call this pattern "Abstract Factory"? Is it an
appropriate name for what it is doing? Why or why not?
top
327
Observations
1. Alexander uses the term, "alive" to characterize good designs. What terms do I suggest
using when it comes to software?
"When you read alive', think robust' and flexible' systems. (p. 189)
ld
2. Good design requires keeping what in mind?
Keeping the big picture in mind. Being able to consider the forest first and then the trees. (p.
189)
or
3. Alexander suggests that the best approach to design involves"complexification." What
does this mean?
Complexification is the approach to design to starts by looking at the problem in its simplest
terms and then adds additional features (distinctions), making the design more complex as we go
because we are adding information (p. 190)
W
5. To Alexander, what relationships does a pattern define?
A pattern defines relationships between the entities in his problem domain (p. 191, 192) This is
why define a pattern as a solution to a problem in a context. The entities describe the context in
which the pattern exists.
Start with context patterns (those that create context for other patterns)
Interpretations
1. I quote Alexander, "But it is impossible to form anything which has the character of
nature by adding preformed parts." What does Alexander mean by this?
Alexander believes that designs that have the "character of nature" are those that humans would
judge has being superior in design. They are "alive" and feel right. He believes that buildings (or
328
in our case, software) that is built simply by assembling stock parts will not feel "alive". They
will have all the charm of 60s style block houses: functional but dead. In software terms, it works
the same way: cobbling together objects does not create solutions that are easily maintained:
robust and flexible. (p. 188, 189)
1. Sometimes, the case that is made for object-oriented programming is that it gives you
small, reusable components that you can assemble to create a program. Does this align with
ld
Alexander or contradict him? Or is Alexander speaking at a different level? Why?
2. Have you ever seen a courtyard or entryway in a house or building that has felt
particularly "dead" or uninviting? As you look at Alexander's description of the
Courtyard pattern, what entities did your courtyard fail to resolve or involve?
or
3. Think of one software project in which you think Alexander's approach would apply or
an approach in which it would not apply. What are the issues? Keep this case in mind as
you read the rest of the book.
top
W
Solving The CAD/CAM Problem with Patterns
Observations
1. What are the three steps to software design with patterns that I use?
TU
For the set of patterns to be analyzed, pick the pattern that provides the most context and apply it
to the conceptual design. Identify additional patterns that are now suggested. Repeat.
Add detail to the conceptual design. Expand the method and class definitions. (p. 199).
JN
2. Define "context."
The seniormost pattern is the pattern that creates the context for the other patterns. When it
comes to applying patterns to a design, we want start with the "seniormost" patterns first and
then work down (p. 203)
329
5. When comparing two patterns, I suggest two rules for discerning which pattern might be
seniormost. What are these rules? Does one pattern define how the other pattern behaves?
ld
Design Patterns Explained. I suggest starting with the canonical form and then mapping classes
and elements of the problem into it. (p. 208)
Interpretations
1. Do I believe that your entire problem can always be defined in terms of patterns? If not,
or
what else is needed?
The answer is "not always." Generally, patterns give you a way to get started with understanding
the problem. However, analysis remains a human activity! (which is good because we still have
jobs!). it is usually the case that the analyst ends up having to identify relationships amongst
concepts in the problem domain. One good approach to this is Commonality / Variability
W
analysis, which has been discussed before. (p. 199)
2. In the CAD/CAM problem, I reject the Abstract Factory as the "seniormost" pattern.
What reasons do they give?
The Abstract Factory requires knowing what classes will be defined. These are defined by other
patterns. Therefore, Abstract Factory depends upon other patterns; they create the context for the
TU
3. In the CAD/CAM problem, what reason(s) do I give for labeling Bridge as senior to
Adapter?
Clearly, there is a relationship between Bridge and Adapter. But Adapter's interfaces cannot be
determined without Bridge. Without the Bridge, Adapter's interfaces simply don't exist. Since
Adapter depends upon Bridge and not vice-versa, Bridge is more senior (p. 205)
JN
1. Once all of the patterns are applied, there are still likely to be more details. I assert that
Alexander's general rules (design by starting with the context) still apply. Does this ever
stop? Is there ever a time when you should go ahead and dive into the details? Isn't that
what "rapid prototyping" suggests? How can you avoid this temptation that all
programmers have? Should you?
330
2. Compare the first solution to the CAD/CAM problem (Figure 13-12) with the new
version (Figure 13-11). What do you like better about the new design?
top
Observations
ld
1. When it comes to choosing how to implement a design, what question do I suggest
asking?
Rather than ask, "Which implementation is better?" ask, for each alternative, "Under what
circumstances would this alternative be better than the other alternative" and then "Which of
or
these circumstances to I have in my problem domain?" (p. 221)
Interpretations
W
1. The "open-closed" principle says, "modules, methods, and classes should be open for
extension while closed for modification." What does this mean?
Bertrand Meyer puts this forward as a way to minimize risk when changing systems. Basically, it
means that we want to be able to extend the capabilities of our systems without substantially
changing it. Design in such a way that the software can absorb new variations without having to
TU
2. In what way does the Bridge pattern illustrate the open-closed principle?
Bridge allows us to add new implementations without changing any existing classes (p. 218).
1. I suggest that even though a design pattern might give you insights into what could
happen, you do not have to build your code to handle those possibilities. How do you decide
which possibilities to handle now and which to be ready for in the future?
2. Give a concrete example of the danger of misapplying a design pattern, based upon your
current work.
top
331
Observations
1. I suggest two approaches to identifying commonalities and variabilities. What are they?
Pick any two items in the problem domain and ask, "is one of these a variation of the other" and
"are both of these a variation of something else".
ld
Look at the problem and identify the major concepts.
Interpretations
1. CVA says you should have only one issue per commonality. Why is this important?
or
Having two issues per commonality leads to confusion in the relationship amongst the concepts.
When the connection is clear, then there is clear and thus strong cohesion amongst concepts.
Design patterns tell you what to do with those concepts, how to relate them based upon good
designs from the past. CVA does not speak about best-practices, leaving that to the designer's
imagination.
TU
1. I state that experienced developers - even more than inexperienced ones - often focus on
entity relationships too early, before they are clear what the right entities are. Is that your
experience? Give an example to confirm or refute this statement.
2. Relate the approach to design - starting with CVA - with Alexander's approach.
JN
top
Observations
332
Each row represents specific, concrete implementations of the generalized concept described in
the row. (p. 296)
Each column represents the specific implementations for each case. (p. 297)
ld
5. Which patterns described in this book might be present in an Analysis Matrix?
In general, any pattern that uses polymorphism could be present in an Analysis Matrix. In this
book, that involves Bridge, Decorator, Template, and Observer. (p. 299).
Interpretations
or
1. At what level of perspective does the Analysis Matrix operate?
The Analysis Matrix is focused on variations in concepts. It is used at the Conceptual Level (p.
293).
W
2. In what way is the Analysis Matrix similar to Commonality/Variability Analysis?
The Analysis Matrix is focused on variations in concepts. It starts by understanding the concept
that a function represents and putting a label onto it. The Analysis Matrix works with these labels
as abstractions for the function. CVA also works by abstracting variations and labeling them. (p.
293).
TU
2. Do you agree with I' observations about users (p. 296)? Can you give examples from
your own experience?
3. Do you believe that the Analysis Matrix is generally useful in most problem domains?
JN
top
Observations
333
Decorators wrap their trailing objects. Each Decorator object wraps its new function around its
trailing object.
Stream I/O
ld
Interpretations
The Decorator pattern helps to decompose the problem into two parts: How to implement the
objects that give the new functionality; and how to organize the objects for each special case
or
2. In discussing the essence of the Decorator, I say that "the structure is not the pattern."
What does this mean? Why is this important?
The Decorator pattern comes into play when there are a variety of optional functions that can
precede or follow another function that is always executed.
W
Implementing the pattern by rote can lead to bad design. Instead, you need to think about the
forces at work in the pattern and then think about ways to implement the intent of the pattern.
Patterns are not recipes.
1. Why do you think the Gang of Four call this pattern "Decorator"? Is it an appropriate
name for what it is doing? Why or why not?
top
Observations
1. According to the Gang of Four, what are structural patterns responsible for?
2. What are the three classifications of patterns, according to the Gang of Four? What is
the fourth classification that I suggest?
334
The GoF specified three types: Structural, Behavioral, and Creational. I suggest "decoupling" as
a fourth type.
ld
The Gang of Four says that the intent of the Observer pattern is to "define a one-to-many
dependency between objects so that when one object changes state, all its dependents are notified
and updated automatically."
Interpretations
or
1. Why are the Bridge and Decorator patterns more correctly classified as structural rather
than behavioral patterns?
They both are tying together functionality, which is what structural patterns do. In the Bridge
pattern, we typically start with abstractions and implementations and then bind them together
with the bridge. In the Decorator pattern, we have an original functional class, and want to
W decorate it with additional functions.
2. One example of the Observer pattern from outside of software is a radio station: It
broadcasts its signal; anyone who is interested can tune in and listen when they want to.
What is another example from "real-life"?
3. Under what conditions should an Observer pattern not be used? When the dependencies
are fixed (or virtually so), adding an Observer pattern probably just adds complexity.
1. I put forward the idea of a "fourth category" of patterns, that somewhat includes
patterns from other categories. Is this a good idea? Why or why not?
JN
top
Observations
1. The Template Method pattern makes the method call in a special way. What is that?
335
The method itself is general. It makes the method call via a reference pointing to one of the
derived classes to handle the special details.
Interpretations
1. According to the Gang of Four, the intent of the Template Method pattern is to "Define
the skeleton of an algorithm in an operation, deferring some steps to subclasses. Redefine
the steps in an algorithm without changing the algorithm's structure" What does this
mean?
ld
It helps us to generalize a common process - at an abstract level - from a set of different
procedures. It helps to identify the common ground between the set of different procedures while
encapsulating the differences in derived classes
2. The Gang of Four calls this a "Template Method". Why do they do this?
or
Because it provides a boilerplate (or a "template") that specifies the generic actions and derived
class implements the specific steps required for the actions to take
3. What is the difference between the Strategy pattern (chapter 9) and the Template
Method pattern?
W
The Template Method pattern is applicable when there are different, but conceptually similar
processes.
The Strategy pattern controls a family of algorithms. They do not have to be conceptually
similar. You choose the algorithm to employ just in time.
TU
top
Observations
A factory is a method, an object, or anything else that is used to instantiate other objects.
2. Name one factory pattern that was shown in a previous chapter. Name the factory
patterns mentioned in this chapter
The Abstract Factory was shown in chapter 11. In this chapter, the factories mentioned are
Builder, Factory Method, Prototype, and Singleton
3. When it comes to managing object creation, what is a good, universal rule to use?
336
An object should either make and/or manage other objects, or it should use other objects but it
should never do both
Interpretations
1. I state that developers who are new to object-oriented programming often lump the
management of object creation in with object instantiation. What is wrong with this?
It can lead to decreased cohesion because an object depends on or more other objects to ensure
ld
work is done before it can successfully continue.
2. I suggest that factories increase cohesion. What is their rationale for saying so?
Factories help to keep together both the functionality and the rules that determine which objects
should be built and/or managed under different circumstances.
or
3. I suggest that factories also help in testing. In what ways is this true?
The "using objects" should behave in exactly the same way with any set of derivatives present. I
should not need to test every possible combination, because I can test each piece individually.
No matter how I combine them, the system will work in the same manner.
W
Opinions and Applications
1. I suggest that factories are useful for more than simply deciding which object to create
or use. They also help with encapsulating design by solving a problem created by patterns?
Evaluate this argument.
TU
top
Observations
1. What type of pattern is the Singleton? What general category of pattern does it belong
to?
JN
Ensure a class only has one instance, and provide a global point of access to it
one
337
5. The Singleton uses a special method to instantiate objects. What is special about this
method?
When this method is called, it checks to see if the object has already been instantiated. If it has,
the method simply returns a reference to the object. If not, the method instantiates it and returns a
reference to the new instance.
To ensure that this is the only way to instantiate an object of this type, I define the constructor of
this class to be protected or private.
ld
5. What do I say is the difference in when to use the Singleton and Double-Checked
Locking patterns?
The distinction between the patterns is that the Singleton pattern is used in single-threaded
applications while the Double-Checked Locking pattern is used in multithreaded applications.
or
Double-Checked must focus on synchronization in creations in case two objects try to create an
object at exactly the same moment. This avoids unnecessary locking. It does this by wrapping
the call to new with another conditional test. Singleton does not have to worry about this.
Interpretations
W
1. I state that they would rather have the objects be responsible for handling their own
single instantiation than to do it globally for the objects. Why is this better?
It also frees other objects from worrying whether the object already exists. They can assume it
TU
does (or will) and that there is only one of that object to reference. They don't have to worry
about getting the right one. As systems grow in size and complexity, trying to manage all of this
quickly can get out of hand. But you have to be careful not to create global variables.
2. Why do you think the Gang of Four call this pattern "Singleton"? Is it an appropriate
name for what it is doing? Why or why not?
JN
3. The authors state, "When it was discovered that the Double Checked Locking pattern as
initially described did not work in Java, many people saw it as evidence that patterns were
over-hyped. I drew exactly the opposite conclusion." Do you agree with their logic? Why or
why not?
top
338
Observations
Look for ways to insulate yourself from the impacts of changes to your system.
ld
2. What two patterns does the Object Pool pattern incorporate?
or
3. What is the intent of the Object Pool pattern? Manages the reuse of objects when a type
of object is expensive to create or only a limited number of objects can be created
Interpretations
W
1. What do the XP community mean by YAGNI?
It reflects the idea that you should build what you need now while ignoring the rest. You should
work on the most important things early, when solving them can make the greatest impact. It also
means you avoid working on things are at a minimum distracting, and typically never used (and
TU
1. Reading widely is an important discipline. You never know when you will find something
you can use. One example is the example they found from Steve Maguire's book, Writing
Solid Code. Give at least one example from your own experienced where this has been true
for you.
JN
top
Factories are responsible for creating objects and ensuring objects are available to be used.
339
You want to defer the decision for instantiating a derivation of another class to a derived class
3. The Factory Method pattern has been implemented in all of the major object-oriented
languages. How has it been used in Java, C#, and C++?
In C#, the GetEnumerator is a Factory method on the differen C# collections where it is present.
In C++, the methods used include begin() and end().
ld
Interpretations
or
2. How does the Factory Method pattern fit in with other factories?
The Factory Method allows these other patterns to defer instantiation to subclasses. One uses the
Factory Method to defer responsibility to subclass objects. The Abstract Factory can use a family
of Factory Methods, one for each different family of objects involved. The Template Method can
W
use a method to handle the instantiation; giving responsibility to that method is the factory.
3. The Gang of Four says that the intent of the Factory Method is to "define an interface
for creating an object, but let subclasses decide which class to instantiate." Why is this
important?
It is not always desirable for a class to have to know how to instantiate derived classes
TU
5. How should you go about deciding whether a method should be public, private, or
protected?
5. This is a small chapter but this is not a small pattern. Think of one example where this
pattern could be used.
JN
top
Observations
1. Several of the patterns have the characteristic of shielding implementations from what?
What is this called? Give examples.
340
They shield implementation details from the Client object. This is one type of encapsulation.
Bridge is one such pattern: It hides from the Client how the Abstraction is implemented. (p. 306)
The Decorator pattern gives a way of decomposing responsibilities into the main set that are
always used (ConcreteComponent) and variations that are options (decorators). (p. 309)
3. As you learn patterns, what five forces and concepts do I urge you to look for?
ld
The five forces to look for are:
or
What are the responsibilities of the objects in this pattern?
How may the pattern itself be a microcosmic example of designing by context? (p. 309)
W
Interpretations
The patterns allow for adding new implementations by hiding details of current implementations.
This reflects the open-closed principle, making systems easier to endure over time
TU
20.Tutorial Topics
Creational patterns
JN
Name Description
341
Define an interface for creating a single object, but let subclasses decide which
Factory method class to instantiate. Factory Method lets a class defer instantiation to subclasses
(dependency injection[15]).
ld
Tactic of delaying the creation of an object, the calculation of a value, or some
other expensive process until the first time it is needed. This pattern appears in
Lazy initialization
the GoF catalog as "virtual proxy", an implementation strategy for
or
the Proxypattern.
Ensure a class has only named instances, and provide global point of access to
Multiton
them.
W
Avoid expensive acquisition and release of resources by recycling objects that
Object pool are no longer in use. Can be considered a generalisation of connection
pool and thread pool patterns.
TU
Specify the kinds of objects to create using a prototypical instance, and create
Prototype
new objects by copying this prototype.
Resource
Ensure that resources are properly released by tying them to the lifespan of
acquisition is
suitable objects.
initialization
JN
Singleton Ensure a class has only one instance, and provide a global point of access to it.
Structural patterns
342
Name Description
Adapter or Convert the interface of a class into another interface clients expect. An adapter
Wrapper or lets classes work together that could not otherwise because of incompatible
Translator. interfaces. The enterprise integration pattern equivalent is the translator.
ld
Decouple an abstraction from its implementation allowing the two to vary
Bridge
independently.
or
Compose objects into tree structures to represent part-whole hierarchies.
Composite Composite lets clients treat individual objects and compositions of objects
uniformly.
W
Attach additional responsibilities to an object dynamically keeping the same
Decorator interface. Decorators provide a flexible alternative to subclassing for extending
functionality.
Proxy Provide a surrogate or placeholder for another object to control access to it.
343
Behavioral Patterns
ld
Name Description
or
Communicates information system-wide.
344
ld
Define a one-to-many dependency between objects where a state
Observer orPublish/subscribe change in one object results in all its dependents being notified and
updated automatically.
or
Servant Define common functionality for a group of classes
Concurrency Patterns
345
Name Description
ld
a scheduler for handling requests.
or
particular state.
locking
Can be unsafe when implemented in some
language/hardware combinations. It can therefore sometimes
be considered an anti-pattern.
346
Messaging
Allows the interchange of information (i.e. messages)
ld
design pattern
between components and applications.
(MDP)
or
use it at the same time.
Read-write lock
WAllows concurrent read access to an object, but requires
exclusive access for write operations.
Thread-specific
Static or "global" memory local to a thread.
storage
JN
21.Known gaps ,if any and inclusion of the same in lecture schedule
347
No gaps since compared JNTU syllabus with NIIT Warangal syllabus both are
same and didnt find any gaps
ld
22Discussion topics
or
1: The Object-Oriented Paradigm
2: The UML - The Unified Modeling Language
3: A Problem That Cries Out for Flexible Code
5: A Standard Object-Oriented Solution
W
5: An Introduction to Design Patterns
6: The Faade Pattern
7: The Adapter Pattern
8: Expanding Our Horizons
TU
348