DP Lecture Notes PDF
DP Lecture Notes PDF
DP Lecture Notes PDF
ON
DESIGN PATTERNS
Mr. R.M.NOORULLAH
Assistant Professor
Mr. M.RAKESH
Assistant Professor
Ms. J.HAREESHA
Assistant Professor
1
CONTENTS
UNIT-I
Introduction:
1. What is a design pattern?
2. Design patterns in Smalltalk MVC
3. Describing Design Patterns
4. The Catalog of Design Patterns
5. Organizing the Catalog
6. How Design Patterns Solve Design Problems
7. How to Select a Design Pattern
8. How to use a Design Pattern.
UNIT-II
A Case Study:
1. Designing a Document Editor Design Problems,
2. Document Structure
3. Formatting
4. Embellishing the User Interface
5. Supporting Multiple Look-and Feel Standards
6. Supporting Multiple Window Systems,
7. User Operations Spelling Checking and Hyphenation,
8. Summary.
9. Creational Patterns: Abstract Factory
10. Builder
11. Factory Method
12. Prototype
13. Singleton
14. Discussion of Creational Patterns
UNIT-III
Structural Pattern Part-I :
1. Adapter
2. Bridge
3. Composite
2
UNIT-IV
Behavioral Patterns Part-I :
1. Chain of Responsibility
2. Command
3. Interpreter
4. Iterator
UNIT-V
Behavioral Patterns Part-II (cont’d):
1. State
2. Strategy
3. Template Method
4. Visitor
5. Discussion of Behavioral Patterns
3
UNIT-I
Introduction
4
4. Consequences
Results and Trade Offs.
Critical for design pattern evaluation.
Often space and time trade offs.
Language strengths and limitations.
(Broken into benefits and drawbacks for this discussion).
5
Easy to maintain and enhancement.
6
Applicability:
• Applicability: What are the situations in which the design patterns can be applied?
• What are example of the poor designs that the pattern can address?
• How can recognize situations?
• Structure: Graphical representation of the classes in the pattern using a notation based
on the object Modeling Technique(OMT).
• Participants: The classes and/or objects participating in the design pattern and their
responsibilities.
Structure:
Graphical representation of the classes in the pattern using a notation based on the
object Modeling Technique(OMT).
Participants:
The classes and/or objects participating in the design pattern and their responsibilities.
Collaborations:
How the participants collaborate to carry out their responsibilities.
Consequences:
How does the pattern support its objectives?
What are the trade-offs and result of using the pattern ?
What aspect of the system structure does it let vary independently?
Implementation:
What pitfalls,hints,or techniques should be aware of when implementing the pattern ?
Are there language-specific issues?
Sample Code:
Code fragments that illustrate how might implement the pattern in c++ or Smalltalk.
Known Uses:
Examples of the pattern found in real systems.
Related Patterns:
What design patterns are closely related to this one? What are the imp differences?
With Which other patterns should this one be used?
7
The Catalog of Design Pattern:
Abstract Factory: Provide an interface for creating families of related or dependent objects
without specifying their concrete classes.
Adaptor: Convert the interface of a class into another interface clients expect.
Bridge: Decouple an abstraction from its implementation so that two can vary independently.
• Builder:
• Separates the construction of the complex object from its representation so that the
same constriction process can create different representations.
• Chain of Responsibility: Avoid coupling the sender of a request to it‘s receiver by
giving more than one object a chance to handle the request. Chain the receiving
objects and pass the request along the chain until an objects handles it.
• Command:
• Encapsulate a request as an object ,thereby letting parameterize clients with different
request, queue or log requests, and support undoable operations.
• Composite:
Compose objects into three objects to represent part-whole hierarchies. Composite lets clients
treat individual objects and compositions of objects uniformly.
• Decorator:
• Attach additional responsibilities to an object dynamically. Decorators provide a
flexible alternative to sub classing for extending functionality.
• Façade: Provide a unified interface to a set of interfaces in a subsystem's Facade
defines a higher-level interface that makes the subsystem easier to use.
• Factory Method:
• Defines an interface for creating an object ,but let subclasses decide which class to
instantiate. Factory Method lets a class defer instantiation to subclasses.
• Flyweight:
• Use sharing to support large numbers of fine-grained objects efficiently.
• Interpreter:
• Given a language, defining a representation of its grammar along with an interpreter
that uses the representation to interpret sentences in the language.
• Memento: Without violating encapsulation, capture and externalize an object‘s
internal state so that object can be restored to this state later.
8
• Observer:Define a one-to-many dependency between objects so that when one object
changes state, all it‘s dependents are notified and updated automatically.
• Prototype:
• Specify the kinds of objects to create using a prototypical instance, and create new
objects by copying this prototype.
• Proxy: Provide a surrogate or placeholder for another object to control access to it.
• Singleton: Ensure a class has only one instance, and provide a point of access to it.
• State:
• Allow an object to alter its behavior when its internal state changes. the object will
appear to change its class.
• Strategy:
• Define a family of algorithms, encapsulate each one, and make them interchangeable.
Strategy lets the algorithm vary independently from clients that use it.
• Template Method:
• Define the Skelton of an operation, deferring some steps to subclasses. Template
method subclasses redefine certain steps of an algorithm without changing the
algorithms structure.
• Visitor:
Represent an operation to be performed on the elements of an object structure.
Visitor lets you define a new operation without changing the classes of the elements
on which it operates.
9
How Design Patterns Solve Design Problems:
• Finding Appropriate Objects
– Decomposing a system into objects is the hard par.t
– OO-designs often end up with classes with no counterparts in real world (low-
level classes like arrays).
Strict modeling of the real world leads to a system that reflects today‘s realities but not
necessarily tomorrows.
– Design patterns identify less-obvious abstractions.
• Determining Object Granularity
– Objects can vary tremendously in size and number
– Facade pattern describes how to represent subsystems as objects
– Flyweight pattern describes how to support huge numbers of objects
10
Specifying Object Interfaces:
• Interface:
– Set of all signatures defined by an object‘s operations.
– Any request matching a signature in the objects interface may be sent to the
object.
– Interfaces may contain other interfaces as subsets.
• Type:
– Denotes a particular interfaces.
– An object may have many types.
– Widely different object may share a type.
– Objects of the same type need only share parts of their interfaces.
– A subtype contains the interface of its super type.
• Dynamic binding, polymorphism.
11
– An object can have many types, and objects of different classes can have the
same type.
• Class versus Interface Inheritance
– class inheritance defines an object‘s implementation in terms of another
object‘s implementation (code and representation sharing).
– interface inheritance (or subtyping) describes when an object can be used in
place of another.
• Many of the design patterns depend on this distinction.
• White-box reuse:
– Reuse by subclassing (class inheritance)
– Internals of parent classes are often visible to subclasses
– works statically, compile-time approach
– Inheritance breaks encapsulation
• Black-box reuse:
– Reuse by object composition
– Requires objects to have well-defined interfaces
– No internal details of objects are visible
12
Inheritance versus Composition
• Two most common techniques for reuse
– class inheritance
• white-box reuse
– object composition
• black-box reuse
• Class inheritance
– advantages
• static, straightforward to use.
• make the implementations being reuse more easily.
• Class inheritance (cont.)
– disadvantages
• the implementations inherited can‘t be changed at run time.
• parent classes often define at least part of their subclasses‘ physical
representation.
• breaks encapsulation.
• implementation dependencies can cause problems when you‘re trying
to reuse a subclass.
• Object composition
– dynamic at run time.
– composition requires objects to respect each others‗ interfaces.
• but does not break encapsulation.
– any object can be replaced at run time.
– Favoring object composition over class inheritance helps you keep each class
encapsulated and focused on one task.
• Object composition (cont.)
– class and class hierarchies will remain small.
– but will have more objects.
13
Delegation:
• Two objects are involved in handling a request: a receiving object delegates
operations to its delegate.
• Makes it easy to compose behaviors at run-time and to change the way they‘re
composed.
• Disadvantage: Dynamic, highly parameterized software is harder to understand
than more static software.
• Delegation is a good design choice only when it simplifies more than it complicates.
• Delegation is an extreme example of object composition.
– parameterized types let you change the types that a class can use.
14
Relating Run-Time and Compile-Time Structures:
• An object-oriented program‘s run-time structure often bears little resemblance to its
code structure.
• The code structure is frozen at compile-time.
• A program‘s run-time structure consists of rapidly changing networks of
communicating objects.
• The distinction between acquaintance and aggregation is determined more by intent
than by explicit language mechanisms
• The system‘s run-time structure must be imposed more by the designer than the
language.
• The distinction between acquaintance and aggregation is determined more by intent
than by explicit language mechanisms.
• The system‘s run-time structure must be imposed more by the designer than the
language.
– each design pattern lets some aspect of system structure vary independently of
other aspects.
• Algorithmic dependencies.
Common Causes of Redesign (cont.)
• Tight coupling.
• Extending functionality by subclassing .
• Inability to alter classes conveniently.
15
Design for Change (cont.)
• Design patterns in application programs.
– Design patterns that reduce dependencies can increase internal reuse.
– Design patterns also make an application more maintainable when they‘re
used to limit platform dependencies and to layer a system.
• Design patterns in toolkits
– A toolkit is a set of related and reusable classes designed to provide useful,
general-purpose functionality.
– Toolkits emphasize code reuse. They are the object-oriented equivalent of
subroutine libraries.
– Toolkit design is arguably harder than application design.
• Design patterns in framework
– A framework is a set of cooperating classes that make up a reusable design for
a specific class of software.
– You customize a framework to a particular application by creating application-
specific subclasses of abstract classes from the framework.
– The framework dictates the architecture of your application.
16
How To Select a Design Pattern:
Consider how design patterns solve design problems.
Scan Intent sections.
Study how patterns interrelate.
Study patterns of like purpose.
Examine a Cause of redesign.
17
Look At the Sample Code section to see a concrete
Example of the pattern in code.
Choose names for pattern participants that are meaningful in the application context.
Define the classes.
18
Unit –II
A Case Study
Design Problems:
• seven problems in Lexis's design:
Document Structure:
The choice of internal representation for the document affects nearly every aspect of
Lexis's design. All editing , formatting, displaying, and textual analysis will require
traversing the representation.
Formatting:
How does Lexi actually arrange text and graphics into lines and columns?
What objects are responsible for carrying out different formatting policies?
How do these policies interact with the document‘s internal representation?
User Operations:
User control Lexi through various interfaces, including buttons and pull-down menus. The
functionality beyond these interfaces is scattered throughout the objects in the application.
19
Document Structure:
Goals:
– present document‘s visual aspects
– drawing, hit detection, alignment
– support physical structure
(e.g., lines, columns)
Constraints/forces:
– treat text & graphics uniformly.
– no distinction between one & many.
Some constraints:
– we should treat text and graphics uniformly.
– our implementation shouldn‘t have to distinguish between single elements and
groups of elements in the internal representation.
20
Recursive Composition:
– a common way to represent hierarchically structured information.
21
• Glyphs:
– an abstract class for all objects that can appear in a document structure.
Three basic responsibilities, they know
• How to draw themselves
• What space they occupy
• Their children and parent.
22
Formatting :
23
• Compositor and Composition (cont):
– The Compositor-Composition class split ensures a strong separation between
code that supports the document‘s physical structure and the code for different
formatting algorithms.
24
• Strategy pattern:
– intent: encapsulating an algorithm in an object.
– Compositors are strategies. A composition is the context for a compositor
strategy.
• Transparent Enclosure:
– inheritance-based approach will result in some problems.
– Composition, Scrollable Composition, Bordered Scrollable Composition.
– object composition offers a potentially more workable and flexible extension
mechanism.
• Monoglyph
– We can apply the concept of transparent enclosure to all glyphs that embellish
other glyphs.
– the class, Monoglyph .
25
26
• Decorator Pattern
– captures class and object relationships that support embellishment by
transparent enclosure.
27
• Factories and Product Classes:
– Factories create product objects.
28
Supporting Multiple Window Systems:
• We‘d like Lexi to run on many existing window systems having different
programming interfaces.
• Can we use an Abstract Factory?
– As the different programming interfaces on these existing window systems,
the Abstract Factory pattern doesn‗t work.
– We need a uniform set of windowing abstractions that lets us take different
window system impelementations and slide any one of them under a common
interface.
• Encapsulating Implementation Dependencies
– The Window class interface encapsulates the things windows tend to do across
window systems
– The Window class is an abstract class
– Where does the implementation live?
29
• Window and WindowImp :
30
• Bridge Pattern
– to allow separate class hierarchies to work together even as they evolve
independently.
User Operations:
• Requirements
– Lexi provides different user interfaces for the operations it supported.
– These operations are implemented in many different classes.
– Lexi supports undo and redo.
• The challenge is to come up with a simple and extensible mechanism that satisfies all
of these needs.
• Encapsulating a Request
– We could parameterize Menu Item with a function to call, but that‘s not
a complete solution.
• it doesn‘t address the undo/redo problem.
• it‘s hard to associate state with a function.
• functions are hard to extent, and it‘s hard to reuse part of them.
– We should parameterize Menu Items with an object, not a function.
• Command Class and Subclasses
– The Command abstract class consists of a single abstract operation called
―Execute‖.
– Menu Item can store a Command object that encapsulates a request.
– When a user choose a particular menu item, the Menu Item simply
calls Execute on its Command object to carry out the request.
31
• Undo ability
– To undo and redo commands, we add an Unexecute operation to Command‘s
interface.
– A concrete Command would store the state of the Command for Unexecute .
– Reversible operation returns a Boolean value to determine if a command is
undoable.
Command History
– a list of commands that have been executed.
32
• The command history can be seen as a list of past commands.
• As new commands are executed they are added to the front of the history.
Undoing the Last Command:
• To undo a command, un execute() is called on the command on the front of the list.
• The ―present‖ position is moved past the last command.
Undoing Previous command:
33
Spelling Checking & Hyphenation:
Goals:
– analyze text for spelling errors.
– introduce potential hyphenation sites.
Constraints/forces:
– support multiple algorithms.
– don‘t tightly couple algorithms with document structure.
Solution: Encapsulate Traversal:
Iterator
– encapsulates a traversal algorithm without exposing representation details to
callers.
– uses Glyph‘s child enumeration operation.
– This is an example of a ―preorder iterator‖.
34
Structure:
Consequences
+ flexibility: aggregate & traversal are independent.
+ multiple iterators & multiple traversal algorithms.
+ additional communication overhead between iterator & aggregate.
Implementation
– internal versus external iterators.
– violating the object structure‘s encapsulation.
– robust iterators .
– synchronization overhead in multi-threaded programs.
– batching in distributed & concurrent programs.
Known Uses
– C++ STL iterators.
– JDK Enumeration, Iterator .
– Unidraw iterator.
Visitor:
• defines action(s) at each step of traversal.
• avoids wiring action(s) into Glyphs.
• iterator calls glyph‘s accept(Visitor) at each node.
• accept() calls back on visitor (a form of ―static polymorphism‖ based on method
overloading by type).
35
void Character::accept (Visitor &v) { v.visit (*this); }
class Visitor {
public:
virtual void visit (Character &);
virtual void visit (Rectangle &);
virtual void visit (Row &);
// etc. for all relevant Glyph subclasses
};
SpellingCheckerVisitor :
• gets character code from each character glyph.
Can define getCharCode() operation just on Character() class
• checks words accumulated from character glyphs.
• combine with PreorderIterator .
36
Accumulating Words:
Interaction Diagram:
• The iterator controls the order in which accept() is called on each glyph in the
composition.
• accept() then ―visits‖ the glyph to perform the desired action.
• The Visitor can be sub-classed to implement various desired actions.
37
Hyphenation Visitor:
• gets character code from each character glyph
• examines words accumulated from character glyphs
• at potential hyphenation point, inserts a...
Concluding Remarks:
• design reuse.
• uniform design vocabulary.
• understanding, restructuring, & team communication.
• provides the basis for automation.
• a ―new‖ way to think about design.
38
Creational Patterns :
– composed
– represented
Creational patterns encapsulates knowledge about which concrete classes the system
uses
Hides how instances of these classes are created and put together
Important if systems evolve to depend more on object composition than on class
inheritance
Emphasis shifts from hardcoding fixed sets of behaviors towards a smaller set of
composable fundamental behaviors
Encapsulate knowledge about concrete classes a system uses
Hide how instances of classes are created and put together
Design patterns that deal with object creation mechanisms, trying to create objects
in a manner suitable to the situation
Make a system independent of the way in which objects are created, composed and
represented
Recurring themes :
Encapsulate knowledge about which concrete classes the system uses (so we can
change them easily later)
Hide how instances of these classes are created and put together (so we can change it
easily later)
Creational patterns let you program to an interface defined by an abstract class that lets
you configure a system with ―product‖ objects that vary widely in structure and functionality
39
Example:
GUI systems.
Multiple look-and-feels.
Simplicity – Make instantiation easier: callers do not have to write long complex code
to instantiate and set up an object (Builder, Prototype pattern).
Creation constraints – Creational patterns can put bounds on who can create objects,
how they are created, and when they are created .
Abstract factory provide an interface for creating families of related or dependent objects
without specifying their concrete classes
• Intent:
Motivation:
40
Solution:
41
Abtract Factory :
Concrete Factory :
Abstract Product :
Concrete Product:
Client:
42
Collaborators :
• The client may use the AbstractFactory interface to initiate creation, or some other
agent may use the AbstractFactory on the client‘s behalf.
Presentation Remark :
• Here, we often use a sequence diagram (event-trace) to show the dynamic interactions
between participants.
• For the Abstract Factory Pattern, the dynamic interaction is simple, and a sequence
diagram would not add much new information.
Consequences :
• You use the Abstract Factory to control the classes of objects the client
creates.
• None of the client code breaks because the abstract interfaces don‘t
change.
43
– It promotes consistency among products.
• It is the concrete factory‘s job to make sure that the right products are
used together.
• Adding a new product requires extending the abstract interface which implies that all
of its derived concrete classes also must change.
• Essentially everything must change to support and use the new product family
• abstract factory interface is extended
• derived concrete factories must implement the extensions
• a new abstract product class is added
• a new product implementation is added
• client has to be extended to use the new product
Implementation
• simple
44
• product classes now have special requirements - they participate in the
creation
– only one virtual create function is needed for the AbstractFactory interface
– all products created by a factory must have the same base class or be able to be
safely coerced to a given type
Know Uses:-
• Interviews
– used to generate ―look and feel‖ for specific user interface objects
– uses the Kit suffix to denote AbstractFactory classes, e.g., WidgetKit and
DialogKit.
ET++
Related Patterns:-
45
Code Examples:-
• Skeleton Example
– Skeleton Code
BUILDER :-
• Intent:
Separate the construction of a complex object from its representation so that the same
construction process can create different representations
• Motivation:
• Solution:
• TextWidgetConverter will produce a complex UI object and lets the user see
and edit the text
46
BUILDER Motivation:-
Applicability:-
– The construction process must allow different representations for the object
that is constructed
BUILDER Structure:-
47
Builder – Collaborations:-
• Client creates Director object and configures it with the desired Builder object
• Builder handles requests from the Director and adds parts to the product
48
• In the previous example,
Discussion:-
• Uses Of Builder
– GUI
49
FACTORY METHOD (Class Creational):-
• Intent:
– Define an interface for creating an object, but let subclasses decide which
class to instantiate.
• Motivation:
– Framework has to create objects as well - must instantiate classes but only
knows about abstract classes - which it cannot instantiate
Motivation:-
50
Applicability:-
Participants:-
• Product
• ConcreteProduct
• Creator
51
– May contain a default implementation of the factory method
– Creator relies on its subclasses to define the factory method so that it returns
an instance of the appropriate Concrete Product.
• ConcreteCreator
Factory Method:-
52
PROTOTYPE (Object Creational):-
• Intent:
– Specify the kinds of objects to create using a prototypical instance, and create
new objects by copying this prototype.
• Motivation:
Motivation:-
PROTOTYPE Motivation:-
53
Applicability:-
• Use the Prototype pattern when a system should be independent of how its products
are created, composed, and represented;
– to avoid building a class hierarchy of factories that parallels the class hierarchy
of products; or when instances of a class can have one of only a few different
combinations of state. It may be more convenient to install a corresponding
number of prototypes and clone them rather than instantiating the class
manually, each time with the appropriate state.
PROTOTYPE Structure:-
54
Participants:
• Prototype (Graphic)
• Client (GraphicTool)
Collaborations:
SINGELTON:-
• Intent:
– Ensure a class only has one instance, and provide a global point of access to it.
• Motivation:
Applicability:-
– when the sole instance should be extensible by subclassing, and clients should
be able to use an extended instance without modifying their code.
55
SINGLETON Structure:-
• Singleton:
• Defines an instance operation that lets clients access its unique interface
• Collaborations:
Singleton:-
56
Singleton – Use When:-
Singleton – Benefits:-
• Helps avoid a central application class with various global object references
• In the Qt toolkit:
• A status bar is required for the application, and various application pieces need to be
able to update the text to display information to the user. However, there is only one
status bar, and the interface to it should be limited. It could be implemented as a
Singleton object, allowing only one instance and a focal point for updates. This
would allow updates to be queued, and prevent messages from being overwritten too
quickly for the user to read them.
57
Singleton Code [1]:-
58
Singleton Code [2]:-
if (_instance ==0) {
_instance=new Singleton;
Return _instance;
Implementation Points:-
• Generally, a single instance is held by the object, and controlled by a single interface.
• Sub classing the Singleton may provide both default and overridden functionality.
59
UNIT-III
Structural patterns
In Software Engineering, Structural Design Patterns are Design Patterns that ease the design
by identifying a simple way to realize relationships between entities.
Adapter
Match interfaces of different classes
Bridge
Separates an object‘s interface from its implementation
Composite
A tree structure of simple and composite objects
Decorator
Add responsibilities to objects dynamically
Facade
A single class that represents an entire subsystem
Flyweight
A fine-grained instance used for efficient sharing
60
Private Class Data
Restricts accessor/mutator access
Proxy
An object representing another object
Rules of thumb
1. Adapter makes things work after they're designed; Bridge makes them work before
they are.
2. Bridge is designed up-front to let the abstraction and the implementation vary
independently. Adapter is retrofitted to make unrelated classes work together.
3. Adapter provides a different interface to its subject. Proxy provides the same
interface. Decorator provides an enhanced interface.
4. Adapter changes an object's interface, Decorator enhances an object's responsibilities.
Decorator is thus more transparent to the client. As a consequence, Decorator supports
recursive composition, which isn't possible with pure Adapters.
5. Composite and Decorator have similar structure diagrams, reflecting the fact that both
rely on recursive composition to organize an open-ended number of objects.
6. Composite can be traversed with Iterator. Visitor can apply an operation over a
Composite. Composite could use Chain of responsibility to let components access
global properties through their parent. It could also use Decorator to override these
properties on parts of the composition. It could use Observer to tie one object structure
to another and State to let a component change its behavior as its state changes.
7. Composite can let you compose a Mediator out of smaller pieces through recursive
composition.
8. Decorator lets you change the skin of an object. Strategy lets you change the guts.
61
9. Decorator is designed to let you add responsibilities to objects without subclassing.
Composite's focus is not on embellishment but on representation. These intents are
distinct but complementary. Consequently, Composite and Decorator are often used in
concert.
10. Decorator and Proxy have different purposes but similar structures. Both describe how
to provide a level of indirection to another object, and the implementations keep a
reference to the object to which they forward requests.
11. Facade defines a new interface, whereas Adapter reuses an old interface. Remember
that Adapter makes two existing interfaces work together as opposed to defining an
entirely new one.
12. Facade objects are often Singleton because only one Facade object is required.
13. Mediator is similar to Facade in that it abstracts functionality of existing classes.
Mediator abstracts/centralizes arbitrary communication between colleague objects, it
routinely "adds value", and it is known/referenced by the colleague objects. In contrast,
Facade defines a simpler interface to a subsystem, it doesn't add new functionality, and
it is not known by the subsystem classes.
14. Abstract Factory can be used as an alternative to Facade to hide platform-specific
classes.
15. Whereas Flyweight shows how to make lots of little objects, Facade shows how to
make a single object represent an entire subsystem.
16. Flyweight is often combined with Composite to implement shared leaf nodes.
17. Flyweight explains when and how State objects can be shared.
Intent
Convert the interface of a class into another interface clients expect. Adapter lets
classes work together that couldn't otherwise because of incompatible interfaces.
Wrap an existing class with a new interface.
Impedance match an old component to a new system
Problem
An "off the shelf" component offers compelling functionality that you would like to reuse,
but its "view of the world" is not compatible with the philosophy and architecture of the
system currently being developed.
62
Discussion
Reuse has always been painful and elusive. One reason has been the tribulation of designing
something new, while reusing something old. There is always something not quite right
between the old and the new. It may be physical dimensions or misalignment. It may be
timing or synchronization. It may be unfortunate assumptions or competing standards.
It is like the problem of inserting a new three-prong electrical plug in an old two-prong wall
outlet – some kind of adapter or intermediary is necessary.
Adapter is about creating an intermediary abstraction that translates, or maps, the old
component to the new system. Clients call methods on the Adapter object which redirects
them into calls to the legacy component. This strategy can be implemented either with
inheritance or with aggregation.
Adapter functions as a wrapper or modifier of an existing class. It provides a different or
translated view of that class.
Structure
Below, a legacy Rectangle component's display() method expects to receive "x, y, w, h"
parameters. But the client wants to pass "upper left x and y" and "lower right x and y". This
incongruity can be reconciled by adding an additional level of indirection – i.e. an Adapter
object.
63
Example
The Adapter pattern allows otherwise incompatible classes to work together by converting
the interface of one class into an interface expected by the clients. Socket wrenches provide
an example of the Adapter. A socket attaches to a ratchet, provided that the size of the drive
is the same. Typical drive sizes in the United States are 1/2" and 1/4". Obviously, a 1/2" drive
ratchet will not fit into a 1/4" drive socket unless an adapter is used. A 1/2" to 1/4" adapter
has a 1/2" female connection to fit on the 1/2" drive ratchet, and a 1/4" male connection to fit
in the 1/4" drive socket.
64
Check list
1. Identify the players: the component(s) that want to be accommodated (i.e. the client),
and the component that needs to adapt (i.e. the adaptee).
2. Identify the interface that the client requires.
3. Design a "wrapper" class that can "impedance match" the adaptee to the client.
4. The adapter/wrapper class "has a" instance of the adaptee class.
5. The adapter/wrapper class "maps" the client interface to the adaptee interface.
6. The client uses (is coupled to) the new interface
65
Rules of thumb
Adapter makes things work after they're designed; Bridge makes them work before they are.
Bridge is designed up-front to let the abstraction and the implementation vary independently.
Adapter is retrofitted to make unrelated classes work together.
Adapter provides a different interface to its subject. Proxy provides the same interface.
Decorator provides an enhanced interface.
Adapter is meant to change the interface of an existing object. Decorator enhances another
object without changing its interface. Decorator is thus more transparent to the application than
an adapter is. As a consequence, Decorator supports recursive composition, which isn't
possible with pure Adapters.
Facade defines a new interface, whereas Adapter reuses an old interface. Remember that
Adapter makes two existing interfaces work together as opposed to defining an entirely new
one.
Intent
Decouple an abstraction from its implementation so that the two can vary
independently.
Publish interface in an inheritance hierarchy, and bury implementation in its own
inheritance hierarchy.
Beyond encapsulation, to insulation
Problem
"Hardening of the software arteries" has occurred by using subclassing of an abstract base
class to provide alternative implementations. This locks in compile-time binding between
interface and implementation. The abstraction and implementation cannot be independently
extended or composed.
66
Motivation
Consider the domain of "thread scheduling".
There are two types of thread schedulers, and two types of operating systems or "platforms".
Given this approach to specialization, we have to define a class for each permutation of these
two dimensions. If we add a new platform (say ... Java's Virtual Machine), what would our
hierarchy look like?
What if we had three kinds of thread schedulers, and four kinds of platforms? What if we had
five kinds of thread schedulers, and ten kinds of platforms? The number of classes we would
have to define is the product of the number of scheduling schemes and the number of
platforms.
67
The Bridge design pattern proposes refactoring this exponentially explosive inheritance
hierarchy into two orthogonal hierarchies – one for platform-independent abstractions, and
the other for platform-dependent implementations.
Discussion
Decompose the component's interface and implementation into orthogonal class hierarchies.
The interface class contains a pointer to the abstract implementation class. This pointer is
initialized with an instance of a concrete implementation class, but all subsequent interaction
from the interface class to the implementation class is limited to the abstraction maintained in
the implementation base class. The client interacts with the interface class, and it in turn
"delegates" all requests to the implementation class.
The interface object is the "handle" known and used by the client; while the implementation
object, or "body", is safely encapsulated to ensure that it may continue to evolve, or be
entirely replaced (or shared at run-time.
Use the Bridge pattern when:
you want run-time binding of the implementation,
you have a proliferation of classes resulting from a coupled interface and numerous
implementations,
you want to share an implementation among multiple objects,
you need to map orthogonal class hierarchies.
Consequences include:
decoupling the object's interface,
improved extensibility (you can extend (i.e. subclass) the abstraction and
implementation hierarchies independently),
68
hiding details from clients.
Bridge is a synonym for the "handle/body" idiom. This is a design mechanism that
encapsulates an implementation class inside of an interface class. The former is the body, and
the latter is the handle. The handle is viewed by the user as the actual class, but the work is
done in the body. "The handle/body class idiom may be used to decompose a complex
abstraction into smaller, more manageable classes. The idiom may reflect the sharing of a
single resource by multiple classes that control access to it (e.g. reference counting)."
Structure
The Client doesn‘t want to deal with platform-dependent details. The Bridge pattern
encapsulates this complexity behind an abstraction "wrapper".
Bridge emphasizes identifying and decoupling "interface" abstraction from "implementation"
abstraction.
Example
The Bridge pattern decouples an abstraction from its implementation, so that the two can vary
independently. A household switch controlling lights, ceiling fans, etc. is an example of the
Bridge. The purpose of the switch is to turn a device on or off. The actual switch can be
implemented as a pull chain, simple two position switch, or a variety of dimmer switches.
69
Check list
1. Decide if two orthogonal dimensions exist in the domain. These independent concepts
could be: abstraction/platform, or domain/infrastructure, or front-end/back-end, or
interface/implementation.
2. Design the separation of concerns: what does the client want, and what do the
platforms provide.
3. Design a platform-oriented interface that is minimal, necessary, and sufficient. Its
goal is to decouple the abstraction from the platform.
4. Define a derived class of that interface for each platform.
5. Create the abstraction base class that "has a" platform object and delegates the
platform-oriented functionality to it.
6. Define specializations of the abstraction class if desired.
Rules of thumb
Adapter makes things work after they're designed; Bridge makes them work before
they are.
Bridge is designed up-front to let the abstraction and the implementation vary
independently. Adapter is retrofitted to make unrelated classes work together.
State, Strategy, Bridge (and to some degree Adapter) have similar solution structures.
They all share elements of the "handle/body" idiom. They differ in intent - that is, they
solve different problems.
70
The structure of State and Bridge are identical (except that Bridge admits hierarchies of
envelope classes, whereas State allows only one). The two patterns use the same
structure to solve different problems: State allows an object's behavior to change along
with its state, while Bridge's intent is to decouple an abstraction from its implementation
so that the two can vary independently.
If interface classes delegate the creation of their implementation classes (instead of
creating/coupling themselves directly), then the design usually uses the Abstract Factory
pattern to create the implementation objects.
Intent
Compose objects into tree structures to represent whole-part hierarchies. Composite lets
clients treat individual objects and compositions of objects uniformly.
Recursive composition
"Directories contain entries, each of which could be a directory."
1-to-many "has a" up the "is a" hierarchy
Problem
Application needs to manipulate a hierarchical collection of "primitive" and "composite"
objects. Processing of a primitive object is handled one way, and processing of a composite
object is handled differently. Having to query the "type" of each object before attempting to
process it is not desirable.
Discussion
Define an abstract base class (Component) that specifies the behavior that needs to be
exercised uniformly across all primitive and composite objects. Subclass the Primitive and
Composite classes off of the Component class. Each Composite object "couples" itself only
to the abstract type Component as it manages its "children".
Use this pattern whenever you have "composites that contain components, each of which
could be a composite".
Child management methods [e.g. addChild(), removeChild()] should normally be defined in
the Composite class. Unfortunately, the desire to treat Primitives and Composites uniformly
requires that these methods be moved to the abstract Component class. See the "Opinions"
section below for a discussion of "safety" versus "transparency" issues.
71
Structure
Composites that contain Components, each of which could be a Composite.
Example
The Composite composes objects into tree structures and lets clients treat individual objects
and compositions uniformly. Although the example is abstract, arithmetic expressions are
Composites. An arithmetic expression consists of an operand, an operator (+ - * /), and
another operand. The operand can be a number, or another arithmetic expresssion. Thus, 2 +
3 and (2 + 3) + (4 * 6) are both valid expressions.
72
Check list
1. Ensure that your problem is about representing "whole-part" hierarchical
relationships.
2. Consider the heuristic, "Containers that contain containees, each of which could be a
container." For example, "Assemblies that contain components, each of which could be
an assembly." Divide your domain concepts into container classes, and containee
classes.
3. Create a "lowest common denominator" interface that makes your containers and
containees interchangeable. It should specify the behavior that needs to be exercised
uniformly across all containee and container objects.
4. All container and containee classes declare an "is a" relationship to the interface.
5. All container classes declare a one-to-many "has a" relationship to the interface.
6. Container classes leverage polymorphism to delegate to their containee objects.
7. Child management methods [e.g. addChild(), removeChild()] should normally be
defined in the Composite class. Unfortunately, the desire to treat Leaf and Composite
objects uniformly may require that these methods be promoted to the abstract
Component class. See the Gang of Four for a discussion of these "safety" versus
"transparency" trade-offs.
Rules of thumb
Composite and Decorator have similar structure diagrams, reflecting the fact that both
rely on recursive composition to organize an open-ended number of objects.
Composite can be traversed with Iterator. Visitor can apply an operation over a
Composite. Composite could use Chain of Responsibility to let components access
global properties through their parent. It could also use Decorator to override these
73
properties on parts of the composition. It could use Observer to tie one object structure
to another and State to let a component change its behavior as its state changes.
Composite can let you compose a Mediator out of smaller pieces through recursive
composition.
Decorator is designed to let you add responsibilities to objects without subclassing.
Composite's focus is not on embellishment but on representation. These intents are
distinct but complementary. Consequently, Composite and Decorator are often used in
concert.
Flyweight is often combined with Composite to implement shared leaf nodes.
Opinions
The whole point of the Composite pattern is that the Composite can be treated atomically,
just like a leaf. If you want to provide an Iterator protocol, fine, but I think that is outside the
pattern itself. At the heart of this pattern is the ability for a client to perform operations on an
object without needing to know that there are many objects inside.
Being able to treat a heterogeneous collection of objects atomically (or transparently) requires
that the "child management" interface be defined at the root of the Composite class hierarchy
(the abstract Component class). However, this choice costs you safety, because clients may
try to do meaningless things like add and remove objects from leaf objects. On the other
hand, if you "design for safety", the child management interface is declared in the Composite
class, and you lose transparency because leaves and Composites now have different
interfaces.
Smalltalk implementations of the Composite pattern usually do not have the interface for
managing the components in the Component interface, but in the Composite interface. C++
implementations tend to put it in the Component interface. This is an extremely interesting
fact, and one that I often ponder. I can offer theories to explain it, but nobody knows for sure
why it is true.
My Component classes do not know that Composites exist. They provide no help for
navigating Composites, nor any help for altering the contents of a Composite. This is because
I would like the base class (and all its derivatives) to be reusable in contexts that do not
require Composites. When given a base class pointer, if I absolutely need to know whether or
not it is a Composite, I will use dynamic_cast to figure this out. In those cases where
dynamic_cast is too expensive, I will use a Visitor.
Common complaint: "if I push the Composite interface down into the Composite class, how
am I going to enumerate (i.e. traverse) a complex structure?" My answer is that when I have
behaviors which apply to hierarchies like the one presented in the Composite pattern, I
typically use Visitor, so enumeration isn't a problem - the Visitor knows in each case, exactly
what kind of object it's dealing with. The Visitor doesn't need every object to provide an
enumeration interface.
Composite doesn't force you to treat all Components as Composites. It merely tells you to put
all operations that you want to treat "uniformly" in the Component class. If add, remove, and
similar operations cannot, or must not, be treated uniformly, then do not put them in the
Component base class. Remember, by the way, that each pattern's structure diagram doesn't
define the pattern; it merely depicts what in our experience is a common realization thereof.
74
Structural Pattern Part-II
Decorator Design Pattern
Intent
Attach additional responsibilities to an object dynamically. Decorators provide a
flexible alternative to subclassing for extending functionality.
Client-specified embellishment of a core object by recursively wrapping it.
Wrapping a gift, putting it in a box, and wrapping the box.
Problem
You want to add behavior or state to individual objects at run-time. Inheritance is not feasible
because it is static and applies to an entire class.
Discussion
Suppose you are working on a user interface toolkit and you wish to support adding borders
and scroll bars to windows. You could define an inheritance hierarchy like ...
But the Decorator pattern suggests giving the client the ability to specify whatever
combination of "features" is desired.
Widget* aWidget = new BorderDecorator(
new HorizontalScrollBarDecorator(
75
new VerticalScrollBarDecorator(
aWidget->draw();
This flexibility can be achieved with the following design
Another example of cascading (or chaining) features together to produce a custom object
might look like ...
Stream* aStream = new CompressingStream(
new ASCII7Stream(
new FileStream("fileName.dat")));
76
Structure
The client is always interested in CoreFunctionality.doThis(). The client may, or may not, be
interested in OptionalOne.doThis() and OptionalTwo.doThis(). Each of these classes always
delegate to the Decorator base class, and that class always delegates to the contained
"wrappee" object.
Example
The Decorator attaches additional responsibilities to an object dynamically. The ornaments
that are added to pine or fir trees are examples of Decorators. Lights, garland, candy canes,
glass ornaments, etc., can be added to a tree to give it a festive look. The ornaments do not
change the tree itself which is recognizable as a Christmas tree regardless of particular
ornaments used. As an example of additional functionality, the addition of lights allows one
to "light up" a Christmas tree.
Another example: assault gun is a deadly weapon on it's own. But you can apply certain
"decorations" to make it more accurate, silent and devastating.
77
Check list
1. Ensure the context is: a single core (or non-optional) component, several optional
embellishments or wrappers, and an interface that is common to all.
2. Create a "Lowest Common Denominator" interface that makes all classes
interchangeable.
3. Create a second level base class (Decorator) to support the optional wrapper classes.
4. The Core class and Decorator class inherit from the LCD interface.
5. The Decorator class declares a composition relationship to the LCD interface, and this
data member is initialized in its constructor.
6. The Decorator class delegates to the LCD object.
7. Define a Decorator derived class for each optional embellishment.
8. Decorator derived classes implement their wrapper functionality - and - delegate to
the Decorator base class.
9. The client configures the type and ordering of Core and Decorator objects.
78
Rules of thumb
Adapter provides a different interface to its subject. Proxy provides the same
interface. Decorator provides an enhanced interface.
Adapter changes an object's interface, Decorator enhances an object's responsibilities.
Decorator is thus more transparent to the client. As a consequence, Decorator supports
recursive composition, which isn't possible with pure Adapters.
Composite and Decorator have similar structure diagrams, reflecting the fact that both
rely on recursive composition to organize an open-ended number of objects.
A Decorator can be viewed as a degenerate Composite with only one component.
However, a Decorator adds additional responsibilities - it isn't intended for object
aggregation.
Decorator is designed to let you add responsibilities to objects without subclassing.
Composite's focus is not on embellishment but on representation. These intents are
distinct but complementary. Consequently, Composite and Decorator are often used in
concert.
Composite could use Chain of Responsibility to let components access global
properties through their parent. It could also use Decorator to override these properties
on parts of the composition.
Decorator and Proxy have different purposes but similar structures. Both describe how
to provide a level of indirection to another object, and the implementations keep a
reference to the object to which they forward requests.
Decorator lets you change the skin of an object. Strategy lets you change the guts.
Intent
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a
higher-level interface that makes the subsystem easier to use.
Wrap a complicated subsystem with a simpler interface.
Problem
A segment of the client community needs a simplified interface to the overall functionality of
a complex subsystem.
Discussion
Facade discusses encapsulating a complex subsystem within a single interface object. This
reduces the learning curve necessary to successfully leverage the subsystem. It also promotes
decoupling the subsystem from its potentially many clients. On the other hand, if the Facade
is the only access point for the subsystem, it will limit the features and flexibility that "power
users" may need.
The Facade object should be a fairly simple advocate or facilitator. It should not become an
all-knowing oracle or "god" object.
79
Structure
Facade takes a "riddle wrapped in an enigma shrouded in mystery", and interjects a wrapper
that tames the amorphous and inscrutable mass of software.
80
Example
The Facade defines a unified, higher level interface to a subsystem that makes it easier to use.
Consumers encounter a Facade when ordering from a catalog. The consumer calls one
number and speaks with a customer service representative. The customer service
representative acts as a Facade, providing an interface to the order fulfillment department, the
billing department, and the shipping department.
81
Check list
1. Identify a simpler, unified interface for the subsystem or component.
2. Design a 'wrapper' class that encapsulates the subsystem.
3. The facade/wrapper captures the complexity and collaborations of the component, and
delegates to the appropriate methods.
4. The client uses (is coupled to) the Facade only.
5. Consider whether additional Facades would add value.
Rules of thumb
Facade defines a new interface, whereas Adapter uses an old interface. Remember
that Adapter makes two existing interfaces work together as opposed to defining an
entirely new one.
Whereas Flyweight shows how to make lots of little objects, Facade shows how to
make a single object represent an entire subsystem.
Mediator is similar to Facade in that it abstracts functionality of existing classes.
Mediator abstracts/centralizes arbitrary communications between colleague objects. It
routinely "adds value", and it is known/referenced by the colleague objects. In contrast,
Facade defines a simpler interface to a subsystem, it doesn't add new functionality, and
it is not known by the subsystem classes.
Abstract Factory can be used as an alternative to Facade to hide platform-specific
classes.
82
Facade objects are often Singletons because only one Facade object is required.
Adapter and Facade are both wrappers; but they are different kinds of wrappers. The
intent of Facade is to produce a simpler interface, and the intent of Adapter is to design
to an existing interface. While Facade routinely wraps multiple objects and Adapter
wraps a single object; Facade could front-end a single complex object and Adapter
could wrap several legacy objects.
Question: So the way to tell the difference between the Adapter pattern and the Facade
pattern is that the Adapter wraps one class and the Facade may represent many classes?
Answer: No! Remember, the Adapter pattern changes the interface of one or more classes
into one interface that a client is expecting. While most textbook examples show the adapter
adapting one class, you may need to adapt many classes to provide the interface a client is
coded to. Likewise, a Facade may provide a simplified interface to a single class with a very
complex interface. The difference between the two is not in terms of how many classes they
"wrap", it is in their intent.
Intent
Use sharing to support large numbers of fine-grained objects efficiently.
The Motif GUI strategy of replacing heavy-weight widgets with light-weight gadgets.
Problem
Designing objects down to the lowest levels of system "granularity" provides optimal
flexibility, but can be unacceptably expensive in terms of performance and memory usage.
Discussion
The Flyweight pattern describes how to share objects to allow their use at fine granularities
without prohibitive cost. Each "flyweight" object is divided into two pieces: the state-
dependent (extrinsic) part, and the state-independent (intrinsic) part. Intrinsic state is stored
(shared) in the Flyweight object. Extrinsic state is stored or computed by client objects, and
passed to the Flyweight when its operations are invoked.
An illustration of this approach would be Motif widgets that have been re-engineered as light-
weight gadgets. Whereas widgets are "intelligent" enough to stand on their own; gadgets exist
in a dependent relationship with their parent layout manager widget. Each layout manager
provides context-dependent event handling, real estate management, and resource services to
its flyweight gadgets, and each gadget is only responsible for context-independent state and
behavior.
Structure
Flyweights are stored in a Factory's repository. The client restrains herself from creating
Flyweights directly, and requests them from the Factory. Each Flyweight cannot stand on its
83
own. Any attributes that would make sharing impossible must be supplied by the client
whenever a request is made of the Flyweight. If the context lends itself to "economy of scale"
(i.e. the client can easily compute or look-up the necessary attributes), then the Flyweight
pattern offers appropriate leverage.
The Ant, Locust, and Cockroach classes can be "light-weight" because their instance-specific
state has been de-encapsulated, or externalized, and must be supplied by the client.
84
Example
The Flyweight uses sharing to support large numbers of objects efficiently. Modern web
browsers use this technique to prevent loading same images twice. When browser loads a
web page, it traverse through all images on that page. Browser loads all new images from
Internet and places them the internal cache. For already loaded images, a flyweight object is
created, which has some unique data like position within the page, but everything else is
referenced to the cached one.
85
Check list
1. Ensure that object overhead is an issue needing attention, and, the client of the class is
able and willing to absorb responsibility realignment.
2. Divide the target class's state into: shareable (intrinsic) state, and non-shareable
(extrinsic) state.
3. Remove the non-shareable state from the class attributes, and add it the calling
argument list of affected methods.
4. Create a Factory that can cache and reuse existing class instances.
5. The client must use the Factory instead of the new operator to request objects.
6. The client (or a third party) must look-up or compute the non-shareable state, and
supply that state to class methods.
Rules of thumb
Whereas Flyweight shows how to make lots of little objects, Facade shows how to
make a single object represent an entire subsystem.
Flyweight is often combined with Composite to implement shared leaf nodes.
Terminal symbols within Interpreter's abstract syntax tree can be shared with
Flyweight.
86
Flyweight explains when and how State objects can be shared.
Intent
Provide a surrogate or placeholder for another object to control access to it.
Problem
You need to support resource-hungry objects, and you do not want to instantiate such objects
unless and until they are actually requested by the client.
Discussion
Design a surrogate, or proxy, object that: instantiates the real object the first time the client
makes a request of the proxy, remembers the identity of this real object, and forwards the
instigating request to this real object. Then all subsequent requests are simply forwarded
directly to the encapsulated real object.
There are four common situations in which the Proxy pattern is applicable.
1. A virtual proxy is a placeholder for "expensive to create" objects. The real object
is only created when a client first requests/accesses the object.
2. A remote proxy provides a local representative for an object that resides in a different
address space. This is what the "stub" code in RPC and CORBA provides.
3. A protective proxy controls access to a sensitive master object. The "surrogate" object
checks that the caller has the access permissions required prior to forwarding the
request.
4. A smart proxy interposes additional actions when an object is accessed. Typical uses
include:
o Counting the number of references to the real object so that it can be freed
automatically when there are no more references (aka smart pointer),
o Loading a persistent object into memory when it's first referenced,
o Checking that the real object is locked before it is accessed to ensure that no
other object can change it.
Structure
By defining a Subject interface, the presence of the Proxy object standing in place of the
RealSubject is transparent to the client.
87
Example
The Proxy provides a surrogate or place holder to provide access to an object. A check or
bank draft is a proxy for funds in an account. A check can be used in place of cash for
making purchases and ultimately controls access to cash in the issuer's account.
88
Check list
1. Identify the leverage or "aspect" that is best implemented as a wrapper or surrogate.
2. Define an interface that will make the proxy and the original component
interchangeable.
3. Consider defining a Factory that can encapsulate the decision of whether a proxy or
original object is desirable.
4. The wrapper class holds a pointer to the real class and implements the interface.
5. The pointer may be initialized at construction, or on first use.
6. Each wrapper method contributes its leverage, and delegates to the wrappee object.
Rules of thumb
Adapter provides a different interface to its subject. Proxy provides the same
interface. Decorator provides an enhanced interface.
Decorator and Proxy have different purposes but similar structures. Both describe how
to provide a level of indirection to another object, and the implementations keep a
reference to the object to which they forward requests.
89
UNIT-IV
Behavioral Patterns
Behavioural Patterns Part-I : Chain of Responsibility, Command, Interpreter, Iterator.
Chain of Responsibility:
• Decouple sender of a request from receiver.
• Give more than one object a chance to handle.
• Flexibility in assigning responsibility.
• Often applied with Composite.
90
Chain of Responsibility (2)
91
Command: Class Diagram
92
Command: Consequences
Consequences:
The object of the command (Receiver) and the algorithm of the command.
(ConcreteCommand) are decoupled.
Invoker is shielded from specific commands.
ConcreteCommands are objects. They can be created and stored.
New ConcreteCommands can be added without changing existing code.
Command:
• You have commands that need to be
– executed,
– undone, or
– queued
• Command design pattern separates
– Receiver from Invoker from Commands
• All commands derive from Command and implement do(), undo(), and redo().
93
Command Design Pattern :
Pattern: Interpreter:
• Intent: Given a language, interpret sentences.
• Participants: Expressions, Context, Client.
• Implementation: A class for each expression type
An Interpret method on each class
A class and object to store the global state (context)
• No support for the parsing process
(Assumes strings have been parsed into exp trees)
94
• Builds tree structure only as needed.
(Or, can automatically build complete trees)
Iterator pattern :
• iterator: an object that provides a standard way to examine all elements of any
collection.
• uniform interface for traversing many different data structures without exposing their
implementations.
• supports concurrent iteration and element removal.
• removes need to know about internal structure of collection or different methods to
access data from different collections.
Pattern: Iterator
objects that traverse collections
95
Iterator interfaces in Java:
public interface java.util.Iterator {
public boolean hasNext();
public Object next();
public void remove();
}
public interface java.util.Collection {
... // List, Set extend Collection
public Iterator iterator();
}
public interface java.util.Map {
...
public Set keySet(); // keys,values are Collections
public Collection values(); // (can call iterator() on them)
}
Iterators in Java:
• all Java collections have a method iterator that returns an iterator for the elements of
the collection.
• can be used to look through the elements of any kind of collection (an alternative to
for loop).
96
Adding your own Iterators :
• when implementing your own collections, it can be very convenient to use Iterators
–discouraged (has nonstandard interface):
public class PlayerList {
public int getNumPlayers() { ... }
public boolean empty() { ... }
public Player getPlayer(int n) { ... }
}
– preferred:
public class PlayerList {
public Iterator iterator() { ... }
public int size() { ... }
public boolean isEmpty() { ... }
}
97
Command: Class Diagram
98
Command: Consequences
Consequences:
The object of the command (Receiver) and the algorithm of the command
(ConcreteCommand) are decoupled.
Invoker is shielded from specific commands.
ConcreteCommands are objects. They can be created and stored.
New ConcreteCommands can be added without changing existing code.
99
Method Combination:
• Build a method from components in different classes
• Primary methods: the ―normal‖ methods; choose the most specific one
• Before/After methods: guaranteed to run;
No possibility of forgetting to call super
Can be used to implement Active Value pattern
• Around methods: wrap around everything;
Used to add tracing information, etc.
• Is added complexity worth it?
Common Lisp: Yes; Most languages: No
100
Behavioural Patterns Part-II
Part-II : Mediator, Memento, Observer
101
The Mediator Pattern:
• The Mediator pattern reduces coupling and simplifies code when several objects must
negotiate a complex interaction.
• Classes interact only with a mediator class rather than with each other.
• Classes are coupled only to the mediator where interaction control code resides.
• Mediator is like a multi-way Façade pattern.
Analogy: a meeting scheduler.
Unmediated
Collaboration
collaboratorB
1: op1() 2.1: op2()
2: op2()
collaboratorA collaboratorC
Mediated
collaboratorB
Collaboration
1.1: op1()
1.5: op2()
1: op() 1.2: op2()
collaboratorA mediator collaboratorC
1.3: op3()
1.4: op4()
collaboratorD
Mediator Collaborator
ColleagueA
ColleagueB
ColleagueC
102
Mediator as a Broker:
Collaborator
«supplier»
ColleagueC
Mediator Behavior:
sd requestService()
consult()
consult()
notify()
consult()
103
Mediators, Façades, and Control Styles:
• The Façade and Mediator patterns provide means to make control more centralized.
• The Façade and Mediator patterns should be used to move from a dispersed to a
delegated style, but not from a delegated to a centralized style.
Summary :
• Broker patterns use a Broker class to facilitate the interaction between a Client and a
Supplier.
• The Façade pattern uses a broker (the façade) to provide a simplified interface to a
complex sub-system.
• The Mediator pattern uses a broker to encapsulate and control a complex interaction
among several suppliers.
Memento Pattern
Intent:
• Capture and externalize an object‘s state without violating encapsulation.
• Restore the object‘s state at some later time.
– Useful when implementing checkpoints and undo mechanisms that let users
back out of tentative operations or recover from errors.
– Entrusts other objects with the information it needs to revert to a previous state
without exposing its internal structure and representations.
Forces:
• Application needs to capture states at certain times or at user discretion. May be used
for:
– Undue / redo
– Log errors or events
– Backtracking
• Need to preserve encapsulation
– Don‘t share knowledge of state with other objects
• Object owning state may not know when to take state snapshot.
104
Motivation:
• Many technical processes involve the exploration of some complex data
structure.
• Often we need to backtrack when a particular path proves unproductive.
Examples are graph algorithms, searching knowledge bases, and text
navigation.
Memento stores a snapshot of another object‘s internal state, exposure of which would violate
encapsulation and compromise the application‘s reliability and extensibility.
A graphical editor may encapsulate the connectivity relationships between objects in a class,
whose public interface might be insufficient to allow precise reversal of a move operation.
• The editor requests a memento from the object before executing move operation.
• Originator creates and returns a memento.
• During undo operation, the editor gives the memento back to the originator.
• Based on the information in the memento, the originator restores itself to its previous
state.
Applicability:
• Use the Memento pattern when:
– A snapshot of an object‘s state must be saved so that it can be restored later,
and direct access to the state would expose implementation details and break
encapsulation.
105
Structure:
Originator Memento
Attribute: Attribute: caretaker
state state
Operation: Operation:
SetMemento(Memento m) GetState( )
CreateMemento( ) SetState( )
state = m->GetState( )
Participants:
• Memento
– Stores internal state of the Originator object. Originator decides how much.
– Protects against access by objects other than the originator.
– Mementos have two interfaces:
• Caretaker sees a narrow interface.
• Originator sees a wide interface.
• Originator
– Creates a memento containing a snapshot of its current internal state.
– Uses the memento to restore its internal state.
106
Caretaker:
• Is responsible for the memento‘s safekeeping.
• Never operates on or examines the contents of a memento.
Event Trace:
CreateMemento( )
new Memento
SetState( )
SetMemento(aMemento)
GetState( )
Collaborations:
• A caretaker requests a memento from an originator, holds it for a time, and passes it
back to the originator.
• Mementos are passive. Only the originator that created a memento will assign or
retrieve its state.
107
Consequences:
Memento has several consequences:
– Memento avoids exposing information that only an originator should manage,
but for simplicity should be stored outside the originator.
– Having clients manage the state they ask for simplifies the originator.
• Using mementos may be expensive, due to copying of large amounts of state or
frequent creation of mementos.
• A caretaker is responsible for deleting the mementos it cares for.
A caretaker may incur large storage costs when it stores mementos.
Implementation:
When mementos get created and passed back to their originator in a predictable sequence,
then Memento can save just incremental changes to originator‘s state.
Known Uses:
Memento is a 2000 film about Leonard Shelby and his quest to revenge the brutal murder of
his wife. Though Leonard is hampered with short-term memory loss, he uses notes and tatoos
to compile the information into a suspect.
Related Patterns
• Command
Commands can use mementos to maintain state for undo mechanisms.
• Iterator
Mementos can be used for iteration.
108
Observer Pattern
• Define a one-to-many dependency, all the dependents are notified and updated
automatically
• The interaction is known as publish-subscribe or subscribe-notify
• Avoiding observer-specific update protocol: pull model vs. push model
• Other consequences and open issues
• Intent:
• Define a one-to-many dependency between objects so that when one object
changes state, all its dependents are notified and updated automatically
• Key forces:
• There may be many observers
• Each observer may react differently to the same notification
• The subject should be as decoupled as possible from the observers to allow
observers to change independently of the subject
Observer
• Many-to-one dependency between objects
• Use when there are two or more views on the same ―data‖
• aka ―Publish and subscribe‖ mechanism
• Choice of ―push‖ or ―pull‖ notification styles
109
Observer: Encapsulating Control Flow
Name: Observer design pattern
Problem description:
Maintains consistency across state of one Subject and many Observers.
Solution:
A Subject has a primary function to maintain some state (e.g., a data structure). One
or more Observers use this state, which introduces redundancy between the states of Subject
and Observer.
Observer invokes the subscribe() method to synchronize the state. Whenever the state
changes, Subject invokes its notify() method to iteratively invoke each Observer.update()
method.
110
Observer: Class Diagram
Observer: Consequences
Consequences:
Decouples Subject, which maintains state, from Observers, who make use of the state.
Can result in many spurious broadcasts when the state of Subject changes.
setState()
notify()
update()
getState()
update()
getState()
111
Observer Pattern [1]
• Need to separate presentational aspects with the data, i.e. separate views and data.
• Classes defining application data and presentation can be reused.
• Change in one view automatically reflected in other views. Also, change in the
application data is reflected in all views.
• Defines one-to-many dependency amongst objects so that when one object changes its
state, all its dependents are notified.
112
Observer Pattern: Observer code
113
Observer Pattern: A Concrete Subject [1]
114
115
Observer Pattern: A Concrete Observer [1]
116
117
Observer Pattern: Main (skeleton)
118
UNIT-V
Behavioral Patterns
Behavioural Patterns Part-II(cont‘d) : State, Strategy, Template Method, Visitor, Discussion
of Behavioural Patterns.
General Description
• A type of Behavioral pattern.
• Allows an object to alter its behavior when its internal state changes. The object will
appear to change its class.
• Uses Polymorphism to define different behaviors for different states of an object.
119
Example I
120
Example II
121
If criteria is fixed, transition can be defined in the context.
More flexible if transition is specified in the State subclass.
Introduces dependencies between subclasses.
Whether to create State objects as and when required or to create-them-
once-and-use-many-times ?
First is desirable if the context changes state infrequently.
Later is desirable if the context changes state frequently.
Pattern: Strategy
objects that hold alternate algorithms to solve a problem
Strategy pattern
• pulling an algorithm out from the object that contains it, and encapsulating the
algorithm (the "strategy") as an object
• each strategy implements one behavior, one implementation of how to solve the same
problem
– how is this different from Command pattern?
• separates algorithm for behavior from object that wants to act
• allows changing an object's behavior dynamically without extending / changing the
object itself
• examples:
– file saving/compression
– layout managers on GUI containers
– AI algorithms for computer game players
122
Strategy example: Card player
// Strategy hierarchy parent
// (an interface or abstract class)
public interface Strategy {
public Card getMove();
}
// setting a strategy
player1.setStrategy(new SmartStrategy());
// using a strategy
Card p1move = player1.move(); // uses strategy
123
Strategy Example: Class Diagram for Mobile Computer
Strategy: Consequences
Consequences:
ConcreteStrategies can be substituted transparently from Context.
Policy decides which Strategy is best, given the current circumstances.
New policy algorithms can be added without modifying Context or Client.
124
Strategy
• You want to
– use different algorithms depending upon the context
– avoid having to change the context or client
• Strategy
– decouples interface from implementation
– shields client from implementations
– Context is not aware which strategy is being used; Client configures the
Context
– strategies can be substituted at runtime
– example: interface to wired and wireless networks
• Make algorithms interchangeable---‖changing the guts‖
• Alternative to subclassing
• Choice of implementation at run-time
• Increases run-time complexity
125
Template Method
Conducted By Raghavendar Japala
Introduction
The DBAnimationApplet illustrates the use of an abstract class that serves as a template for
classes with shared functionality.
An abstract class contains behavior that is common to all its subclasses. This behavior is
encapsulated in nonabstract methods, which may even be declared final to prevent any
modification. This action ensures that all subclasses will inherit the same common behavior
and its implementation.
The abstract methods in such templates ensure the interface of the subclasses and require that
context specific behavior be implemented for each concrete subclass.
126
Frozen Spots and Hot Spots
A template method uses hook methods to define a common behavior.
Template method describes the fixed behaviors of a generic class, which are sometimes
called frozen spots.
Hook methods indicate the changeable behaviors of a generic class, which are sometimes
called hot spots.
127
ConcreteClass (e.g., Bouncing-Ball2) which implements the hook methods (e.g.,
paintFrame()) to carry out subclass specific steps of the algorithm defined in the template
method.
128
129
What to Expect from Design Patterns, A Brief History, The Pattern Community An
Invitation, A Parting Thought.
130
An adjacent to existing methods:
1. Object-oriented design methods are supposed to promote good design, to teach new
designers how to design well, and standardize the way designs are developed.
2. A design method typically defines a set of notations (usually graphical) for modeling
various aspects of design along with a set of rules that govern how and when to use
each notation.
3. Design methods usually describe problems that occur in a design, how to resolve them
and how to evaluate design. But then have not been able to capture the experience of
expert designers.
4. A full fledged design method requires more kinds of patterns than just design patterns
there can also be analysis patterns, user interface design patterns, or performance
tuning patterns but the design patterns are an essential part, one that‘s been missing
until now.
131
A Brief History of Design Patterns
• 1979--Christopher Alexander pens The Timeless Way of Building
– Building Towns for Dummies
– Had nothing to do with software
• 1994--Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (the Gang of
Four, or GoF) publish Design patterns: Elements of Reusable Object-Oriented
Software
– Capitalized on the work of Alexander
– The seminal publication on software design patterns.
132
Grand’s Classifications of Design Pattern:
• Fundamental patterns
• Creational patterns
• Partitioning patterns
• Structural patterns
• Behavioral patterns
• Concurrency patterns
133
In fact ,we think it‘s unlikely that there will ever be a compete pattern language for soft
-ware.
But certainly possible to make one that is more complete.
A Parting Thought.
The best designs will use many design patterns that dovetail And intertwine to produce a
greater whole.
As Alexander says:
It is possible to make buildings by stringing together pattern‘s In a rather loose way,
A building made like this , is an assembly of patterns. it is not
Dense. It is not profound. but it is also possible to put pattern‘s
together
In such a way that many patterns overlap in the same physical Space: the building is
very dense; it has many meaning captured In a small space; and through this density, it
becomes profound.
134