Lecture 5
Design Patterns
MAIN CONTENT
Creational patterns
Structural patterns
Behavioral patterns
INTRODUCTION TO DESIGN PATTERN
What is design pattern ?
o Solutions to general problems faced in software
development
o Industry standard approach to solve recurring problems
o Programming language independent strategies for solving
the common object-oriented design problems.
INTRODUCTION TO DESIGN PATTERN
Why do we need design pattern ?
o Promotes reusability: more robust and maintainable code
o Faster development, code easier to understand, debug
o Provides standard terminology
o Provides the solutions that help to define the system
architecture.
o Captures the software engineering experiences.
o Provides transparency to the design of an application.
INTRODUCTION TO DESIGN PATTERN
When should we use design pattern ?
o We must use the design patterns during the analysis and
requirement phase of Software Development Life Cycle.
o Design patterns ease the analysis and requirement phase
of SDLC by providing information based on prior hands-
on experiences.
3 MAIN TYPES OF DESIGN PATTERN
CREATIONAL PATTERN
Is concerned with the way of creating objects
Is used when a decision must be made at the time of
instantiation of a class
Way to create objects while hiding logic
Does not use the “new” operator
Offers more flexibility in deciding which objects need to be
created for a given case
Solution to instantiate an object in the best possible way for the
situation
SINGLETON PATTERN
Defines a class that has only one instance and provides a global
point of access to it
A class must ensure that only single instance should be created
and single object can be used by all other classes.
There are 2 main forms:
Early Instantiation: creation of instance at load time.
Lazy Instantiation: creation of instance when required.
Usage:
Is mostly used in multi-threaded and database applications.
Is used in logging, caching, thread pools, configuration settings
SINGLETON PATTERN
Example: JDBC
FACTORY PATTERN
Super class with many sub classes – return one of the sub-classes
Refer to newly created object using a common interface
Is used to define an interface or abstract class for creating an
object but let the subclasses decide which class to instantiate.
Usage:
When a class doesn't know what sub-classes will be required
to create
When a class wants that its sub-classes specify the objects to
be created
When the parent classes choose the creation of objects to its
sub-classes
FACTORY PATTERN
Example: Electricity Bill
ABSTRACT FACTORY PATTERN
Defines an interface or abstract class for creating families of
related (or dependent) objects but without specifying their
concrete sub-classes.
Lets a class returns a factory of classes
Usage:
When the system needs to be independent of how its object
are created, composed, and represented.
When the family of related objects has to be used together,
then this constraint needs to be enforced.
When you want to provide a library of objects that does not
show implementations and only reveals interfaces.
ABSTRACT FACTORY PATTERN
Example: Bank
BUILDER PATTERN
Constructs a complex object from simple objects using step-by-
step approach
Is mostly used when object can't be created in single step like in
the de-serialization of a complex object
Advantages:
Provides clear separation between the construction and
representation of an object
Provides better control over construction process
Supports to change the internal representation of objects
BUILDER PATTERN
Example: Pizza
PROTOTYPE PATTERN
Does cloning of an existing object instead of creating new one and
can also be customized as per the requirement.
Should be followed, if the cost of creating a new object is expensive
and resource intensive.
Usage:
When the classes are instantiated at runtime.
When the cost of creating an object is expensive or complicated.
When you want to keep the number of classes in an application
minimum.
When the client application needs to be unaware of object
creation and representation.
PROTOTYPE PATTERN
Example: Employee
STRUCTURAL PATTERN
Provides different ways to create a class structure
Uses inheritance to compose interfaces & define ways to
create objects to get new functionality
Is concerned with how classes and objects can be composed,
to form larger structures.
Simplifies the structure by identifying the relationships.
Focuses on how the classes inherit from each other and how
they are composed from other classes.
ADAPTER PATTERN
Converts the interface of a class into another interface that a
client wants
Provides the interface according to client requirement while
using the services of a class with a different interface
Usage:
When an object needs to utilize an existing class with an
incompatible interface.
When you want to create a reusable class that cooperates
with classes which don't have compatible interfaces.
ADAPTER PATTERN
Example: Credit Card
COMPOSITE PATTERN
Allows clients to operate in generic manner on objects that may
or may not represent a hierarchy of objects
Advantages:
Defines class hierarchies that contain primitive objects.
Makes easier to you to add new kinds of components.
Usage:
When you want to represent a full or partial hierarchy of
objects.
When the responsibilities are needed to be added
dynamically to the individual objects without affecting other
objects.
COMPOSITE PATTERN
Example: Employee
DECORATOR PATTERN
Attaches flexible additional responsibilities to an object
dynamically
Uses composition instead of inheritance to extend the
functionality of an object at runtime.
Usage:
When you want to transparently and dynamically add
responsibilities to objects without affecting other objects.
When you want to add responsibilities to an object that you
may want to change in future.
Extending functionality by sub-classing is no longer
practical.
DECORATOR PATTERN
Example: Food
BRIDGE PATTERN
Decouples the functional abstraction from the
implementation so that the two can vary independently
Usage:
When you don't want a permanent binding between the
functional abstraction and its implementation.
When both the functional abstraction and its
implementation need to extended using sub-classes.
It is mostly used in those places where changes are made
in the implementation does not affect the clients.
BRIDGE PATTERN
Example: Question
FACADE PATTERN
Provides a unified and simplified interface to a set of
interfaces in a subsystem, therefore it hides the complexities
of the subsystem from the client
Describes a higher-level interface that makes the sub-system
easier to use
Usage:
When you want to provide simple interface to a complex
sub-system.
When several dependencies exist between clients and the
implementation classes of an abstraction.
FACADE PATTERN
Example: MobileShop
FLYWEIGHT PATTERN
Reuses existing similar kind of objects by storing them and
create new object when no matching object is found
Advantages:
It reduces the number of objects.
It reduces the amount of memory and storage devices
required if the objects are persisted
Usage:
When an application uses number of objects
When the storage cost is high because of the quantity of
objects.
When the application does not depend on object identity.
PROXY PATTERN
Provides the control for accessing the original object
We can perform many operations like hiding the information
of original object, on demand loading etc.
Usage:
Virtual Proxy scenario
Protective Proxy scenario
Remove Proxy scenario
Smart Proxy scenario
PROXY PATTERN
Example: InternetAccess
BEHAVIORAL PATTERN
Concerned with communication & better interaction between
objects
Provides loose coupling and flexibility to extend easily
Is concerned with the interaction and responsibility of
objects.
The interaction between the objects should be in such a way
that they can easily talk to each other and still should be
loosely coupled.
The implementation and the client should be loosely coupled
in order to avoid hard coding and dependencies.
CHAIN OF RESPONSIBILITY PATTERN
Avoids coupling the sender of a request to its receiver by
giving multiple objects a chance to handle the request.
Normally each receiver contains reference of another
receiver. If one object cannot handle the request then it
passes the same to the next receiver and so on.
Usage:
When more than one object can handle a request and the
handler is unknown.
When the group of objects that can handle the request
must be specified in dynamic way.
CHAIN OF RESPONSIBILITY PATTERN
Example: Logger
COMMAND PATTERN
Encapsulates a request under an object as a command and pass
it to invoker object.
Invoker object looks for the appropriate object which can handle
this command and pass the command to the corresponding
object and that object executes the command
Usage:
When you need parameterize objects according to action
perform.
When you need to create, execute requests at different times.
When you need to support rollback, logging or transaction
functionality.
COMMAND PATTERN
Example: ActionListener
INTERPRETER PATTERN
Defines a representation of grammar of a given language,
along with an interpreter that uses this representation to
interpret sentences in the language
Usage:
When the grammar of the language is not complicated.
When the efficiency is not a priority.
INTERPRETER PATTERN
Example: Pattern
ITERATOR PATTERN
To access the elements of an aggregate object sequentially
without exposing its underlying implementation
Usage:
When you want to access a collection of objects without
exposing its internal representation.
When there are multiple traversals of objects need to be
supported in the collection.
ITERATOR PATTERN
Example: Iterator
MEDIATOR PATTERN
Defines an object that encapsulates how a set of objects interact
Advantages:
Decouples the number of classes.
Simplifies object protocols.
Centralizes the control.
Usage:
It is commonly used in message-based systems likewise chat
applications.
When the set of objects communicate in complex but in well-
defined ways.
MEDIATOR PATTERN
Example: ChatRoom
MEMENTO PATTERN
Restores the state of an object to its previous state".
Must do this without violating Encapsulation.
Advantages:
It preserves encapsulation boundaries.
It simplifies the originator.
Usage:
It is used in Undo and Redo operations in most software.
It is also used in database transactions.
MEMENTO PATTERN
Example: Memento
OBSERVER PATTERN
Defines a one-to-one dependency so that when one object
changes state, all its dependents are notified and updated
automatically
Usage:
When the change of a state in one object must be reflected
in another object without keeping the objects tight
coupled.
When the framework we writes and needs to be enhanced
in future with new observers with minimal changes.
OBSERVER PATTERN
Example: Observer
STATE PATTERN
The class behavior changes based on its state
We create objects which represent various states and a context
object whose behavior varies as its state object changes.
Usage:
When the behavior of object depends on its state and it must
be able to change its behavior at runtime according to the
new state.
It is used when the operations have large, multipart
conditional statements that depend on the state of an object.
STAGE PATTERN
Example: State
STRATEGY PATTERN
Defines a family of functionality, encapsulate each one, and
make them interchangeable
Usage:
When the multiple classes differ only in their behaviors.
It is used when you need different variations of an
algorithm.
STRATEGY PATTERN
Example: Strategy
TEMPLATE PATTERN
Define the skeleton of a function in an operation, deferring
some steps to its subclasses
Usage:
It is used when the common behavior among sub-classes
should be moved to a single common class by avoiding the
duplication.
TEMPLATE PATTERN
Example: Game
THANK YOU
FOR LISTENING !