4 - 1 Design Patterns Lecture Notes (R19)
4 - 1 Design Patterns Lecture Notes (R19)
4 - 1 Design Patterns Lecture Notes (R19)
DESIGN PATTERNS
UNIT-IV
Creational Patterns: Abstract Factory
1. Builder
2. Factory Method
3. Prototype
4. Singleton
5. Discussion of Creational Patterns
UNIT-IV
Structural Pattern
1. Adapter
2. Bridge
3. Composite
4. Decorator
5. Façade
6. Flyweight
7. Proxy
UNIT-V
Behavioral Patterns
1. Chain of Responsibility
2. Command
3. Interpreter
4. Iterator
5. Mediator
6. Memento
7. Observer
8. State
9. Strategy
10.Template Method
11.Visitor
12.What to Expect from Design Patterns
Introduction
• 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.
• 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
• 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‘retrying
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 eachclass
encapsulated and focused on one task.
• Object composition (cont.)
– class and class hierarchies will remain small.
– but will have more objects.
• 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.
– each design pattern lets some aspect of system structure vary independentlyof
other aspects.
• Algorithmic dependencies.
Common Causes of Redesign (cont.)
• Tight coupling.
• Extending functionality by subclassing .
• Inability to alter classes conveniently.
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.
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.
• 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 .
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.
Command History
– a list of commands that have been executed.
• To undo a command, un execute() is called on the command on the front of the list.
• The ―present‖ posit ion is moved past the last command.
Undoing Previous command:
Applicability:
– require multiple traversal algorithms over a container
– require a uniform traversal interface over different containers
– when container classes & traversal algorithm must vary independently
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.
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 .
Interaction Diagram:
• The iterator controls the order in which accept() is called on each glyph in the
composition.
• accept() then ―visit s‖ the glyph to perform the desired action.
• The Visitor can be sub-classed to implement various desired actions.
Concluding Remarks:
• design reuse.
• uniform design vocabulary.
• understanding, restructuring, & team communication.
• provides the basis for automation.
• a ―new‖ way to think about design.
– created
– 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 createobjects
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
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:
Concrete Factory :
Abstract Product :
Concrete Product:
Client:
• 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.
• 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
– 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:-
• 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
Applicability:-
– The construction process must allow different representations for the object
that is constructed
BUILDER Structure:-
• Client creates Director object and configures it with the desired Builder object
• Builder handles requests from the Director and adds parts to the product
Discussion:-
• Uses Of Builder
– GUI
• 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:-
Participants:-
• Product
• ConcreteProduct
• Creator
– Creator relies on its subclasses to define the factory method so that it returns
an instance of the appropriate Concrete Product.
• ConcreteCreator
Factory Method:-
• Intent:
– Specify the kinds of objects to create using a prototypical instance, and create
new objects by copying this prototype.
• Motivation:
Motivation:-
PROTOTYPE Motivation:-
• 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:-
• 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.
• Singleton:
• Defines an instance operation that lets clients access its unique interface
• Collaborations:
Singleton:-
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.
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.
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
Rules of thumb
1. Adapter makes things work after they're designed; Bridge makes them work before
theyare.
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 thesame
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 ofobjects.
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.
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.
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.
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.
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.
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),
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.
Rules of thumb
• Adapter makes things work after they're designed; Bridge makes them work before
theyare.
• 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.
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.
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.
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 ofobjects.
• Composite can be traversed with Iterator. Visitor can apply an operation over a
Composite. Composite could use Chain of Responsibility to let componentsaccess
global properties through their parent. It could also use Decorator to override these
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.
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(
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")));
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.
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.
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.
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
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.
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.
Intent
• Provide a surrogate or placeholder for another object to control access to it.
• Use an extra level of indirection to support distributed, controlled, or intelligent
access.
• Add a wrapper and delegation to protect the real component from undue complexity.
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 adifferent
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. Typicaluses
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.
Rules of thumb
• Adapter provides a different interface to its subject. Proxy provides thesame
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.
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.
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().
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)
Iterator pattern :
• iterator: an object that provides a standard way to examine all elements ofany
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
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).
Problem description:
Encapsulates requests so that they can be executed, undone, or queued independently
of the request.
Solution:
A Command abstract class declares the interface supported by all
ConcreteCommands. ConcreteCommands encapsulate a service to be applied to a Receiver.
The Client creates ConcreteCommands and binds them to specific Receivers. The Invoker
actually executes a command.
Unmediated
Collaboration
collaboratorB
1: op1() 2.1: op2()
2: op2()
collaboratorA collaboratorC
Mediated
Collaboration collaboratorB
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
Collaborator
«supplier»
ColleagueC
Mediator Behavior:
sd requestService()
notify()
consult()
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 toa
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.
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.
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.
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.
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.
• 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
• Cho ice of ―push‖ or ―pull‖ notification st yles
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()
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.
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
Problem description:
Decouple a policy-deciding class from a set of mechanisms, so that
different mechanisms can be changed transparently.
Example:
A mobile computer can be used with a wireless network, or
connected to an Ethernet, with dynamic switching between networks based on location and
network costs.
Solution:
A Client accesses services provided by a Context.
The Context services are realized using one of several mechanisms, as decided by a Policy
object.
The abstract class Strategy describes the interface that is common to all mechanisms that
Context can use. Policy class creates a ConcreteStrategy object and configures Context to use
it.
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.
• 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
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.
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.