Chapter Two
Design Patterns
1
What are design patterns
In software engineering, a design pattern is a general repeatable solution to a
commonly occurring problem in software design.
A design pattern isn't a finished design that can be transformed directly into code. It
is a description or template for how to solve a problem that can be used in many
different situations.
Design patterns can speed up the development process by providing tested, proven
development paradigms.
Effective software design requires considering issues that may not become visible
until later in the implementation.
Reusing design patterns helps to prevent subtle issues that can cause major
problems and improves code readability for coders and architects familiar with the
patterns.
2
Cont…
Often, people only understand how to apply certain software
design techniques to certain problems.
Design patterns provide general solutions, documented in a
format that doesn't require specifics tied to a particular problem.
A design patterns are well-proved solution for solving the
specific problem/task.
In addition, patterns allow developers to communicate using
well-known, well understood names for software interactions.
3
Cont…
design patterns are programming language independent strategies for
solving the common object-oriented design problems. That means, a
design pattern represents an idea, not a particular implementation.
By using the design patterns you can make your code more flexible,
reusable and maintainable.
use the design patterns during the analysis and requirement phase of
SDLC(Software Development Life Cycle).
Design patterns can be categorized into three main types based on their
purpose and area of focus: Creational Patterns, Structural Patterns
and Behavioral Patterns
4
Advantage of design pattern:
They are reusable in multiple projects.
They provide the solutions that help to define the system
architecture.
They provide transparency to the design of an application.
They are well-proved and testified solutions since they have been
built upon the knowledge and experience of expert software
developers.
Design patterns don’t guarantee an absolute solution to a problem.
They provide clarity to the system architecture and the possibility
5 of building a better system.
Creational design patterns
Creational design patterns are concerned with the way of creating
objects.
These design patterns are used when a decision must be made at the time
of instantiation of a class (i.e. creating an object of a class).
These design patterns are all about class instantiation.
This pattern can be further divided into class-creation patterns and
object-creational patterns.
While class-creation patterns the process of creating instances of classes,
object-creation patterns focused on the process of creating individual
objects within a program. Examples of object-creation patterns include
6 Prototype Pattern, Object Pool Pattern
Cont…
Some common creational design patterns:
Factory Method- Defines an interface for creating objects in a
superclass but allows subclasses to alter the type of objects that will
be created.
Abstract Factory- Creates an instance of several families of classes.
Singleton- A class of which only a single instance can exist
Prototype- A fully initialized instance to be copied or cloned
Builder - Separates object construction from its representation
Object Pool- Avoid expensive acquisition and release of resources by
recycling objects that are no longer in use
7
Factory Method Pattern
A Factory Pattern or Factory Method Pattern says that just define an
interface or abstract class for creating an object but let the subclasses
decide which class to instantiate.
In other words, subclasses are responsible to create the instance of the
class.
The Factory Method Pattern is also known as Virtual Constructor.
Advantage of Factory Design Pattern
Factory Method Pattern allows the sub-classes to choose the type of
objects to create.
It promotes the loose-coupling by eliminating the need to bind
application specific classes into the code.
8
Usage of Factory Design Pattern
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.
9
UML for Factory Method Pattern
We are going to create a Plan abstract class and concrete classes that extends the Plan
abstract class. A factory class GetPlanFactory is defined as a next step.
Calculate Electricity Bill : GenerateBill class will use GetPlanFactory to get a Plan
object. It will pass information (DOMESTICPLAN / COMMERCIALPLAN /
INSTITUTIONALPLAN) to GetPalnFactory to get the type of object it needs.
10
Abstract Factory Pattern
Abstract Factory Pattern says that just define an interface or abstract class for
creating families of related (or dependent) objects but without specifying
their concrete sub-classes.
That means Abstract Factory lets a class returns a factory of classes. So, this is
the reason that Abstract Factory Pattern is one level higher than the Factory
Pattern.
An Abstract Factory Pattern is also known as Kit.
Advantage of Abstract Factory Pattern
Abstract Factory Pattern isolates the client code from concrete
(implementation) classes.
It eases the exchanging of object families.
It promotes consistency among objects
11
Usage of Abstract Factory Pattern
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 the system needs to be configured with one of a multiple
family of objects.
12
UML for Abstract Factory Pattern
We are going to create a Bank interface and a Loan abstract
class as well as their sub-classes.
Then we will create AbstractFactory class as next step.
Then after we will create concrete classes, BankFactory, and
LoanFactory that will extends AbstractFactory class
After that, AbstractFactoryPatternExample class uses the
FactoryCreator to get an object of AbstractFactory class.
See the diagram carefully is given below:
13
Cont…
14
Singleton design pattern
Singleton Pattern says that just "define a class that has only one
instance and provides a global point of access to it".
In other words, a class must ensure that only single instance should
be created and single object can be used by all other classes.
There are two forms of singleton design pattern
Early Instantiation: creation of instance at load time.
Lazy Instantiation: creation of instance when required.
Advantage of Singleton design pattern
Saves memory because object is not created at each request.
15 Only single instance is reused again and again
UML of Singleton design pattern
16
How to create Singleton design pattern?
To create the singleton class, we need to have static member
of class, private constructor and static factory method.
Static member: It gets memory only once because of
static, it contains the instance of the Singleton class.
Private constructor: It will prevent to instantiate the
Singleton class from outside the class.
Static factory method: This provides the global point of
access to the Singleton object and returns the instance to
the caller.
17
Cont…
Let's see the example of singleton design pattern using early instantiation.
File: A.java
class A{
private static A obj=new A();//Early, instance will be created at load time
private A(){}
public static A getA(){
return obj;
}
public void doSomething(){
//write your code
}
}
18
Prototype Design Pattern
Prototype Pattern says that cloning of an existing object instead
of creating new one and can also be customized as per the
requirement.
This pattern should be followed, if the cost of creating a new
object is expensive and resource intensive.
The main advantages of prototype pattern are as follows:
It reduces the need of sub-classing.
It hides complexities of creating objects.
The clients can get new objects without knowing which type of
object it will be.
19
Usage of Prototype Pattern
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.
20
UML for Prototype Pattern
21
Cont…
We are going to create an interface Prototype that contains a
method getClone() of Prototype type.
Then, we create a concrete class EmployeeRecord which
implements Prototype interface that does the cloning of
EmployeeRecord object.
PrototypeDemo class will uses this concrete class
EmployeeRecord.
22
Builder Design Pattern
Builder Pattern says that "construct a complex object from
simple objects using step-by-step approach"
It is mostly used when object can't be created in single step like
in the de-serialization of a complex object.
Advantage of Builder Design Pattern
It provides clear separation between the construction and
representation of an object.
It provides better control over construction process.
It supports to change the internal representation of objects.
23
UML for Builder Pattern Example
24
Cont…
Example of Builder Design Pattern
To create simple example of builder design pattern, you need to
follow 6 following steps.
Create Packing interface
Create 2 abstract classes CD and Company
Create 2 implementation classes of Company: Sony and
Samsung
Create the CDType class
Create the CDBuilder class
Create the BuilderDemo class
25
Object Pool Pattern
Object Pool Pattern says that " to reuse the object that are
expensive to create".
Basically, an Object pool is a container which contains a
specified amount of objects. When an object is taken from the
pool, it is not available in the pool until it is put back. Objects
in the pool have a lifecycle: creation, validation and destroy.
A pool helps to manage available resources in a better way.
There are many using examples: especially in application
servers there are data source pools, thread pools etc.
26
Advantage of Object Pool design pattern
It boosts the performance of the application significantly.
It is most effective in a situation where the rate of initializing a class instance
is high.
It manages the connections and provides a way to reuse and share them.
It can also provide the limit for the maximum number of objects that can be
created.
Usage:
When an application requires objects which are expensive to create. Eg:
there is a need of opening too many connections for the database then it
takes too longer to create a new one and the database server will be
overloaded.
When there are several clients who need the same resource at different
27
times.
UML for Object Pool Pattern
28
Structural design patterns
Structural design patterns are concerned with how classes and
objects can be composed, to form larger structures.
The structural design patterns simplifies the structure by
identifying the relationships.
These patterns focus on, how the classes inherit from each other
and how they are composed from other classes.
These design patterns are all about Class and Object composition.
Structural object-patterns define ways to compose objects to
obtain new functionality.
29
Types of structural design patterns
There are following 7 types of structural design patterns.
1. Adapter Pattern - Adapting an interface into another according to
client expectation.
2. Bridge Pattern - Separating abstraction (interface) from
implementation.
3. Composite Pattern - Allowing clients to operate on hierarchy of
objects.
4. Decorator Pattern - Adding functionality to an object dynamically.
5. Facade Pattern - Providing an interface to a set of interfaces.
6. Flyweight Pattern - Reusing an object by sharing it.
7. proxy Pattern - Representing another object.
30
Adapter Pattern
An Adapter Pattern says that just "converts the interface of a
class into another interface that a client wants".
In other words, to provide the interface according to client
requirement while using the services of a class with a different
interface.
The Adapter Pattern is also known as Wrapper.
Advantage of Adapter Pattern
It allows two or more previously incompatible objects to
interact.
31
It allows reusability of existing functionality.
Cont…
It is used:
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.
32
Cont…
UML for Adapter Pattern
33
Bridge Pattern
A Bridge Pattern says that just "decouple the functional
abstraction from the implementation so that the two can
vary independently".
The Bridge Pattern is also known as Handle or Body.
Advantage of Bridge Pattern
It enables the separation of implementation from the interface.
It improves the extensibility.
It allows the hiding of implementation details from the client.
34
Con…
Usage of Bridge Pattern
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.
35
Composite Pattern
Compose objects into tree structures to represent whole-part
hierarchies.
Composite lets clients treat individual objects and compositions
of objects uniformly.
Recursive composition
1-to-many "has a" up the "is a" hierarchy
36
Cont…
It is used:
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.
Where the responsibility of object may vary from time to
time.
37
Cont…
UML for Composite Pattern
38
Cont…
Elements used in Composite Pattern: the 4 elements of composite pattern.
1) Component
Declares interface for objects in composition.
Implements default behavior for the interface common to all classes as appropriate.
Declares an interface for accessing and managing its child components.
2) Leaf
Represents leaf objects in composition. A leaf has no children.
Defines behavior for primitive objects in the composition.
3) Composite
Defines behavior for components having children.
Stores child component.
Implements child related operations in the component interface.
4) Client
Manipulates objects in the composition through the component interface.
39
Cont…
Example of Composite Pattern
40
Decorator Pattern
A Decorator Pattern says that just "attach a flexible additional
responsibilities to an object dynamically".
In other words, The Decorator Pattern uses composition instead of
inheritance to extend the functionality of an object at runtime.
Advantage of Decorator Pattern
It provides greater flexibility than static inheritance.
It enhances the extensibility of the object, because changes are made by
coding new classes.
It simplifies the coding by allowing you to develop a series of
functionality from targeted classes instead of coding all of the behavior
41 into the object.
Cont…
It is used:
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.
42
Cont…
Example
43
Facade Pattern
A Facade Pattern says that just "just provide a unified and
simplified interface to a set of interfaces in a subsystem, therefore
it hides the complexities of the subsystem from the client".
In other words, Facade Pattern describes a higher-level interface that
makes the sub-system easier to use.
Practically, every Abstract Factory is a type of Facade.
Advantage of Facade Pattern
It shields the clients from the complexities of the sub-system
components.
It promotes loose coupling between subsystems and its clients.
44
Cont…
It is used:
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.
45
Flyweight Pattern
A Flyweight Pattern says that just "to reuse already existing similar
kind of objects by storing them and create new object when no
matching object is found".
Advantage of Flyweight Pattern
It reduces the number of objects.
It reduces the amount of memory and storage devices required if the
objects are persisted
Usage of Flyweight Pattern
When an application uses number of objects
When the storage cost is high because of the quantity of objects.
46 When the application does not depend on object identity.
Proxy Pattern
Provide a replacement or placeholder for another object to control
access to it.
Use an extra level of indirection to support distributed, controlled, or
intelligent access.
Add a wrapper and delegation to protect the real component from
unnecessary complexity.
47
Proxy Pattern
Usage of Proxy Pattern :
It can be used in Virtual Proxy scenario---Consider a situation where there is multiple database call to
extract huge size image. Since this is an expensive operation so here we can use the proxy pattern which
would create multiple proxies and point to the huge size memory consuming object for further processing.
The real object gets created only when a client first requests/accesses the object and after that we can just
refer to the proxy to reuse the object. This avoids duplication of the object and hence saving memory.
It can be used in Protective Proxy scenario---It acts as an authorization layer to verify that whether the
actual user has access the appropriate content or not. For example, a proxy server which provides restriction
on internet access in office. Only the websites and contents which are valid will be allowed and the
remaining ones will be blocked.
It can be used in Remote Proxy scenario---A remote proxy can be thought about the stub in the RPC call.
The remote proxy provides a local representation of the object which is present in the different address
location. Another example can be providing interface for remote resources such as web service or REST
resources.
It can be used in Smart Proxy scenario---A smart proxy provides additional layer of security by
48 interposing specific actions when the object is accessed. For example, to check whether the real object is
locked or not before accessing it so that no other objects can change it.
Cont…
UML for Proxy Pattern:
49
Behavioral Design Patterns
Behavioral design patterns are concerned with the interaction
and responsibility of objects.
In these design patterns, 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.
That means the implementation and the client should be loosely
coupled in order to avoid hard coding and dependencies.
50
Cont…
There are 12 types of behavioral design patterns:
1. Chain of Responsibility Pattern
2. Command Pattern
3. Interpreter Pattern
4. Iterator Pattern
5. Mediator Pattern
6. Memento Pattern
7. Observer Pattern
8. State Pattern
9. Strategy Pattern
10. Template Pattern
11. Visitor Pattern
51 12. Null Object
Chain of Responsibility Pattern
In chain of responsibility, sender sends a request to a chain of
objects. The request can be handled by any object in the chain.
A Chain of Responsibility Pattern says that just "avoid coupling
the sender of a request to its receiver by giving multiple
objects a chance to handle the request". For example, an ATM
uses the Chain of Responsibility design pattern in money giving
process.
In other words, each receiver contains reference of another
receiver. If one object cannot handle the request then it passes the
52 same to the next receiver and so on.
Cont…
Advantage of Chain of Responsibility Pattern
It reduces the coupling.
It adds flexibility while assigning the responsibilities to objects.
It allows a set of classes to act as one; events produced in one class
can be sent to other handler classes with the help of composition.
Usage of Chain of Responsibility Pattern:
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.
53
Cont…
UML for Chain of Responsibility Pattern:
54
Command Pattern
A Command Pattern says that "encapsulate 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".
It is also known as Action or Transaction.
Advantage of command pattern
It separates the object that invokes the operation from the object that
actually performs the operation.
It makes easy to add new commands, because existing classes
55 remain unchanged.
Cont…
Usage of command pattern:
When you need parameterize objects according to an action perform.
When you need to create and execute requests at different times.
When you need to support rollback, logging or transaction functionality.
These are the following participants of the Command Design pattern:
Command This is an interface for executing an operation.
ConcreteCommand This class extends the Command interface and implements
the execute method. This class creates a binding between the action and the
receiver.
Client This class creates the ConcreteCommand class and associates it with the
receiver.
Invoker This class asks the command to carry out the request.
56 Receiver This class knows to perform the operation.
Cont…
UML for command pattern:
57
Interpreter Pattern
An Interpreter Pattern says that "to define a representation of
grammar of a given language, along with an interpreter that
uses this representation to interpret sentences in the
language".
Basically the Interpreter pattern has limited area where it can be
applied. We can discuss the Interpreter pattern only in terms of
formal grammars but in this area there are better solutions that is
why it is not frequently used.
This pattern can applied for parsing the expressions defined in
58 simple grammars and sometimes in simple rule engines.
Cont…
Advantage of Interpreter Pattern
It is easier to change and extend the grammar.
Implementing the grammar is straightforward.
Usage of Interpreter pattern
When the grammar of the language is not complicated.
When the efficiency is not a priority.
59
Cont…
UML for Interpreter Pattern
60
Iterator Pattern
Iterator Pattern is used "to access the elements of an aggregate
object sequentially without exposing its underlying
implementation".
The Iterator pattern is also known as Cursor.
In collection framework, we are now using Iterator that is
preferred over Enumeration.
Advantage of Iterator Pattern
It supports variations in the traversal of a collection.
It simplifies the interface to the collection.
61
Cont…
Usage of Iterator Pattern
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.
62
Cont…
63
Mediator Pattern
A Mediator Pattern says that "to define an object that encapsulates how a set
of objects interact".
I will explain the Mediator pattern by considering a problem. When we begin
with development, we have a few classes and these classes interact with each
other producing results. Now, consider slowly, the logic becomes more complex
when functionality increases. Then what happens? We add more classes and
they still interact with each other but it gets really difficult to maintain this code
now. So, Mediator pattern takes care of this problem.
Mediator pattern is used to reduce communication complexity between
multiple objects or classes. This pattern provides a mediator class which
normally handles all the communications between different classes and supports
easy maintainability of the code by loose coupling.
64
Cont…
Benefits
It decouples the number of classes.
It simplifies object protocols.
It centralizes the control.
The individual components become simpler and much easier to deal
with because they don't need to pass messages to one another.
Usage
It is commonly used in message-based systems likewise chat
applications.
When the set of objects communicate in complex but in well-defined
65 ways.
Cont…
66
Memento Pattern
A Memento Pattern says that "to restore the state of an object to its
previous state". But it must do this without violating Encapsulation.
Such case is useful in case of error or failure.
The Memento pattern is also known as Token.
Undo or backspace or ctrl+z is one of the most used operation in an
editor. Memento design pattern is used to implement the undo
operation. This is done by saving the current state of the object as it
changes state.
Benefits:
It preserves encapsulation boundaries.
67 It simplifies the originator.
Cont…
Usage:
It is used in Undo and Redo operations in most software.
It is also used in database transactions.
68
Observer Pattern
An Observer Pattern says that "just define a one-to-one
dependency so that when one object changes state, all its
dependents are notified and updated automatically".
The observer pattern is also known as Dependents or Publish-
Subscribe.
Benefits:
It describes the coupling between the objects and the observer.
It provides the support for broadcast-type communication.
69
Cont…
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.
70
State Pattern
A State Pattern says that "the class behavior changes based on
its state".
In State Pattern, we create objects which represent various
states and a context object whose behavior varies as its state
object changes.
The State Pattern is also known as Objects for States.
Benefits:
It keeps the state-specific behavior.
It makes any state transitions explicit.
71
Cont…
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
72
Strategy Pattern
A Strategy Pattern says that "defines a family of functionality, encapsulate
each one, and make them interchangeable".
The Strategy Pattern is also known as Policy.
Benefits:
It provides a substitute to sub-classing.
It defines each behavior within its own class, eliminating the need for
conditional statements.
It makes it easier to extend and incorporate new behavior without changing
the application.
Usage:
When the multiple classes differ only in their behaviors. e.g. Servlet API.
It is used when you need different variations of an algorithm.
73
Cont…
UML for Strategy Pattern:
74
Template Pattern
A Template Pattern says that "just define the skeleton of a
function in an operation, deferring some steps to its
subclasses".
Benefits:
It is very common technique for reusing the code.
Usage:
It is used when the common behavior among sub-classes
should be moved to a single common class by avoiding the
duplication.
75
Cont…
UML for Template Pattern:
76