0% found this document useful (0 votes)
88 views42 pages

Behavioural Design Patterns

This document provides an introduction and overview of design patterns. It discusses what design patterns are, their elements and purpose. It describes how design patterns solve common design problems and increase reuse. It also outlines the catalog of known design patterns organized by type (creational, structural, behavioral). Specific patterns like abstract factory, adapter and builder are mentioned.

Uploaded by

Akula Sandeep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views42 pages

Behavioural Design Patterns

This document provides an introduction and overview of design patterns. It discusses what design patterns are, their elements and purpose. It describes how design patterns solve common design problems and increase reuse. It also outlines the catalog of known design patterns organized by type (creational, structural, behavioral). Specific patterns like abstract factory, adapter and builder are mentioned.

Uploaded by

Akula Sandeep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

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

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).

Design patterns can be subjective.


One person‘s pattern may be another person‘s primitive building block.
The focus of the selected design patterns are:
Object and class communication.
Customized to solve a general design problem.
Solution is context specific.
Design patterns in Smalltalk MVC:
 The Model/View/Controller triad of classes
is used to build user interfaces in Smalltalk-80
 MVC consists of three kinds of objects.
 M->>MODEL is the Application object.
 V->>View is the screen presentation.
 C->>Controller is the way the user interface reacts to user
input MVC decouples to increase flexibility and reuse.
MVC decouples views and models by establishing a subscribe/notify protocol between them.
A view must ensure that its appearance must reflects the state of the model.
Whenever the model‘s data changes, the model notifies views that depends on it.
You can also create new views for a model without
Rewriting it.
 The below diagram shows a model and three views.
 The model contains some data values, and the views defining a
spreadsheet, histogram, and pie chart display these data in various ways.
 The model communicates with it‘s values change, and the views communicate with
the model to access these values.
 Feature of MVC is that views can be nested.
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

Easy to maintain and enhancement.

Describing Design Patterns:


 Graphical notations ,while important and useful, aren‘t sufficient.
They capture the end product of the design process as relationships between classes
and objects.
By using a consistent format we describe the design pattern .
Each pattern is divided into sections according to the following template.
 Pattern Name and Classification:
 it conveys the essence of the pattern succinctly good name is vital, because it will
become part of design vocabulary.
 Intent: What does the design pattern do?
 What is it‘s rational and intend?
 What particular design issue or problem does it address?
 Also Known As: Other well-known names for the pattern, if any.
 Motivation:
 A scenario that illustrates a design problem and how the class and object structures
in the pattern solve the problem.
 The scenario will help understand the more abstract description of the pattern
that follows.
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

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

The Catalog of Design Pattern:

(Categories of Design pattern)


Creational: concern the process of object creation
Structural: the composition of classes or objects
Behavioral: characterize the ways in which classes or objects interact and distribute
responsibility

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

• 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.
Scope: whether the pattern applies primarily to classes or to ob
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
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
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

Structural Pattern Part-I :


1. Adapter
2. Bridge
Structural Pattern Part-II :
1. Decorator
2. Façade
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

Creational Patterns :

 Abstracts instantiation process


 Makes system independent of how its objects are

– 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

What are creational patterns?

 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.

Interviews GUI class library.


Multiple look-and-feels.
Abstract Factories for different screen components.

Generic instantiation – Objects are instantiated without having to identify a specific


class type in client code (Abstract Factory, Factory) .
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 Pattern

Abstract factory provide an interface for creating families of related or dependent objects
without specifying their concrete classes
• Intent:

– Provide an interface for creating families of related or dependent


objects without specifying their concrete classes
Also Known As: Kit.

Motivation:

User interface toolkit supports multiple look-and-feel standards (Motif, Presentation


Manager).
Different appearances and behaviors for UI widgets
Apps should not hard-code its widgets
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

Solution:

• Abstract Widget Factory class

• Interfaces for creating each basic kind of widget

• Abstract class for each kind of widgets,

• Concrete classes implement specific look-and-feel.


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

Abtract Factory :

Declares interface for operations that create abstract product objects

Concrete Factory :

– Implements operations to create concrete product objects

Abstract Product :

– Declares an interface for a type of product object.

Concrete Product:

– Defines a product object to be created by concrete factory

– Implements the abstract product interface

Client:

– Uses only interfaces declared by Abstract Factory and


AbstractProduct classes.
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

Collaborators :

• Usually only one ConcreteFactory instance is used for an activation, matched to a


specific application context. It builds a specific product family for client use -- the
client doesn‘t care which family is used -- it simply needs the services appropriate for
the current context.
• 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 :

• The Abstract Factory Pattern has the following benefits:

– It isolates concrete classes from the client.


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.

• None of the client code breaks because the abstract interfaces


don‘t change.
• Because the abstract factory creates a complete family of products,
the whole product family changes when the concrete factory is
changed.
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

– It promotes consistency among products.

• It is the concrete factory‘s job to make sure that the right products are
used together.
More benefits of the Abstract Factory Pattern

– It supports the imposition of constraints on product families, e.g., always


use A1 and B1 together, otherwise use A2 and B2 together.
• The Abstract Factory pattern has the following liability:

– Adding new kinds of products to existing factory is difficult.

• 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

• Concrete factories are often implemented as singletons.

• Creating the products

– Concrete factory usually use the factory method.

• simple

• new concrete factory is required for each product family

– alternately concrete factory can be implemented using prototype.

• only one is needed for all families of products


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

•product classes now have special requirements - they participate in the


creation
• Defining extensible factories by using create function with an argument

– 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

– uses the Kit suffix to denote AbstractFactory classes, e.g., WidgetKit


and DialogKit.
– also includes a layoutKit that generates different composite objects
depending on the needs of the current context
ET++
– another windowing library that uses the AbstractFactory to achieve
portability across different window systems (X Windows and SunView).

Related Patterns:-

• Factory Method -- a ―virtual‖ constructor

• Prototype -- asks products to clone themselves

• Singleton -- allows creation of only a single instance


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

Code Examples:-

• Skeleton Example

– Abstract Factory Structure

– Skeleton Code

• Neural Net Example

– Neural Net Physical Structure

– Neural Net Logical Structure

– Simulated Neural Net Example

BUILDER :-

• Intent:

Separate the construction of a complex object from its representation so that the same
construction process can create different representations
• Motivation:

• RTF reader should be able to convert RTF to many text format

• Adding new conversions without modifying the reader should be easy

• Solution:

• Configure RTFReader class with a Text Converter object

• Subclasses of Text Converter specialize in different conversions and formats

• TextWidgetConverter will produce a complex UI object and lets the user see
and edit the text
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:-

• Use the Builder pattern when

– The algorithm for creating a complex object should be independent of


the parts that make up the object and how they are assembled
– The construction process must allow different representations for the object
that is constructed

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

• Director notifies Builder whenever a part of the product should be built

• Builder handles requests from the Director and adds parts to the product

• Client retrieves the product from the Builder


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

Why do we use Builder?

• In the previous example,

– We can either determine all the arguments


or determine nothing and just construct.
We can‘t determine arguments partially.
– We can‘t control whole process to
Create an instance.
– Restriction of ways to Create an Object

– Bad Abstraction & Flexibility

Discussion:-

• Uses Of Builder

– Parsing Program(RTF converter)

– 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

FACTORY METHOD (Class Creational):-

• Intent:

– Define an interface for creating an object, but let subclasses decide which
class to instantiate.
– Factory Method lets a class defer instantiation to subclasses.

• Motivation:

– Framework use abstract classes to define and maintain relationships


between objects
– Framework has to create objects as well - must instantiate classes but only
knows about abstract classes - which it cannot instantiate
Motivation:-

• Motivation: Factory method encapsulates knowledge of which subclass to create


- moves this knowledge out of the framework
• Also Known As: Virtual Constructor

FACTORY METHOD Motivation:-


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

Applicability:-

• Use the Factory Method pattern when

– a class can´t anticipate the class of objects it must create.

– a class wants its subclasses to specify the objects it creates.

– classes delegate responsibility to one of several helper subclasses,


and you want to localize the knowledge of which helper subclass
is the delegate.
FACTORY METHOD Structure:-

Participants:-

• Product

– Defines the interface of objects the factory method creates

• ConcreteProduct

– Implements the product interface

• Creator

– Declares the factory method which returns object of type product


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

– 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

– Overrides factory method to return instance of ConcreteProduct

Factory Method:-

• Defer object instantiation to subclasses

• Eliminates binding of application-specific subclasses

• Connects parallel class hierarchies

• A related pattern is AbstractFactory


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

PROTOTYPE (Object Creational):-

• Intent:

– Specify the kinds of objects to create using a prototypical instance, and create
new objects by copying this prototype.
• Motivation:

– Framework implements Graphic class for graphical components


and GraphicTool class for tools manipulating/creating those
components
Motivation:-

– Actual graphical components are application-specific

– How to parameterize instances of Graphic Tool class with type of objects


to create?
– Solution: create new objects in Graphic Tool by cloning a prototype
object instance
PROTOTYPE Motivation:-
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

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)

– Declares an interface for cloning itself

• ConcretePrototype (Staff, WholeNote, HalfNote)

– Implements an interface for cloning itself

• Client (GraphicTool)

– Creates a new object by asking a prototype to clone itself


Collaborations:
• A client asks a prototype to clone Itself.

SINGELTON:-

• Intent:

– Ensure a class only has one instance, and provide a global point of access to it.

• Motivation:

– Some classes should have exactly one instance


(one print spooler, one file system, one window manager)

– A global variable makes an object accessible but doesn‘t prohibit


instantiation of multiple objects
– Class should be responsible for keeping track of its sole interface

Applicability:-

• Use the Singleton pattern when

– there must be exactly one instance of a class, and it must be accessible to


clients from a well-known access point.
– when the sole instance should be extensible by subclassing, and clients
should be able to use an extended instance without modifying their code.
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

SINGLETON Structure:-

Participants and Collaborations:-

• Singleton:

• Defines an instance operation that lets clients access its unique interface

• Instance is a class operation (static in Java)

• May be responsible for creating its own unique instance

• Collaborations:

• Clients access a Singleton instance solely through Singleton‘s Instance operation.

Singleton:-

• Ensures a class has only one instance

• Provides a single point of reference


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

Singleton – Use When:-

• There must be exactly one instance of a class.

• May provide synchronous access to avoid deadlocks.

• Very common in GUI toolkits, to specify the connection to the


OS/Windowing system
Singleton – Benefits:-

• Controls access to a scarce or unique resource

• Helps avoid a central application class with various global object references

• Subclasses can have different implementations as required. Static or global


references don‘t allow this
• Multiple or single instances can be allowed

Singleton – Example 1:-

• An Application class, where instantiating it makes a connection to the base operating


system and sets up the rest of the toolkit‘s framework for the user interface.
• In the Qt toolkit:

QApplication* app = new QApplication(argc, argv)

Singleton – Example 2:-

• A status bar is required for the application, and various application pieces need to be
able to update the text to display information to the user. However, there is only one
status bar, and the interface to it should be limited. It could be implemented as a
Singleton object, allowing only one instance and a focal point for updates. This
would allow updates to be queued, and prevent messages from being overwritten
too quickly for the user to read them.
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

Singleton Code [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

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.
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 Pattern Part

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

1. 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.
2. 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.
3. 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.
4. Facade objects are often Singleton because only one Facade object is required.
5. 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.
6. Abstract Factory can be used as an alternative to Facade to hide platform-specific
classes.
7. Whereas Flyweight shows how to make lots of little objects, Facade shows how to
make a single object represent an entire subsystem.
8. Flyweight is often combined with Composite to implement shared leaf nodes.
9. Flyweight explains when and how State objects can be shared.
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

Adapter Design Patterns

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.

The Adapter could also be thought of as a "wrapper".


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
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

 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.

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.

Composite Design Pattern

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.

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.
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")));

aStream->putString( "Hello world" );


The solution to this class of problems involves encapsulating the original object inside an
abstract wrapper interface. Both the decorator objects and the core object inherit from this
abstract interface. The interface uses recursive composition to allow an unlimited number of
decorator "layers" to be added to each core object.
Note that this pattern allows responsibilities to be added to an object, not methods to an
object's interface. The interface presented to the client must remain constant as successive
layers are specified.
Also note that the core object's identity has now been "hidden" inside of a decorator object.
Trying to access the core object directly is now a problem.
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.
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

Facade Design Pattern:-

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.

SubsystemOne and SubsystemThree do not interact with the internal components of


SubsystemTwo. They use the SubsystemTwoWrapper "facade" (i.e. the higher level
abstraction).

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.

You might also like