Behavioural Design Patterns
Behavioural Design Patterns
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT COMPLETE SOLUTION …
YOU NEED TO JUSTIFY YOUR ANSWER for each question IN TEST-1 TEST 2 AND SO ON
CONTENTS
CO1
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
9. TDD AND REFACTORING (REFER CLASS NOTES AND LAB WORKBOOK NOTES FOR
THIS)
1
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
Introduction
What is a Design Pattern?
• Each pattern Describes a problem which occurs over and over again in our
environment , Design patterns represent the best practices used by
experienced object-oriented software developers.
• Design patterns are solutions to general problems that software developers
faced during software development.
• These solutions were obtained by trial and error by numerous software
developers over quite a substantial period of time.
• Design Pattern Elements
1. Pattern Name
Handle used to describe the design problem.
Increases vocabulary.
Eases design discussions.
Evaluation without implementation details.
2. Problem
Describes when to apply a pattern.
May include conditions for the pattern to be applicable.
Symptoms of an inflexible design or limitation.
3. Solution
Describes elements for the design.
Includes relationships, responsibilities, and collaborations.
Does not describe concrete designs or implementations.
A pattern is more of a template.
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
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).
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?
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
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.
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
The following is Co2 theory notes only and for programs refer creational patterns
material separately
Co2 topics
Creational Patterns:
1. Abstract Factory
2. Factory Method
3. Singleton
4. Discussion of Creational Patterns
Creational Patterns :
– created
– composed
– represented
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)
Benefits of creational patterns :
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
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
Example:
GUI systems.
Abstract factory provide an interface for creating families of related or dependent objects
without specifying their concrete classes
• Intent:
Motivation:
Solution:
Abtract Factory :
Concrete Factory :
Abstract Product :
Concrete Product:
Client:
Collaborators :
•
You use the Abstract Factory to control the classes of objects the
client creates.
• Product names are isolated in the implementation of the
ConcreteFactory, clients use the instances through their
abstract interfaces.
– Exchanging product families is easy.
• It is the concrete factory‘s job to make sure that the right products are
used together.
More benefits of the Abstract Factory Pattern
• 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
– it is difficult to implement subclass specific operations
Know Uses:-
• Interviews
– used to generate ―look and feel‖ for specific user interface objects
Related Patterns:-
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
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
BUILDER Motivation:-
Applicability:-
BUILDER Structure:-
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
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
Discussion:-
• Uses Of Builder
– GUI
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
• Intent:
– Define an interface for creating an object, but let subclasses decide which
class to instantiate.
– Factory Method lets a class defer instantiation to subclasses.
• Motivation:
Applicability:-
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:
Applicability:-
• Use the Prototype pattern when a system should be independent of how its products
are created, composed, and represented;
– when the classes to instantiate are specified at run-time, for example,
by dynamic loading; or
– 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:-
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
Participants:
• Prototype (Graphic)
• Client (GraphicTool)
SINGELTON:-
• Intent:
– Ensure a class only has one instance, and provide a global point of access to it.
• Motivation:
Applicability:-
SINGLETON Structure:-
• Singleton:
• Defines an instance operation that lets clients access its unique interface
• Collaborations:
Singleton:-
• Helps avoid a central application class with various global object references
• 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.
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
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.
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
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
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.
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.
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.
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
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.
===================================================================
Bridge Design Pattern
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.
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
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.
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),
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
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.
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.
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
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.
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
Structure
Composites that contain Components, each of which could be a Composite.
Menus that contain menu items, each of which could be a menu.
Row-column GUI layout managers that contain widgets, each of which could be a row-
column GUI layout manager.
Directories that contain files, each of which could be a directory.
Containers that contain Elements, each of which could be a Container.
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.
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
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
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.
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.
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
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(
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
new VerticalScrollBarDecorator(
new Window( 80, 24 ))));
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")));
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.
This is a complimentary copy DP NOTES FOR EASY REFERENCE ONLY THIS IS NOT
COMPLETE SOLUTION … YOU NEED TO JUSTIFY YOUR ANSWER as application oriented
for each question IN TEST-1 TEST 2 AND SO ON
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.
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.
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.