You are on page 1of 42

Java Design Pattern

“Design Patterns are recurring


solution to design problems”
Presentation By: Himanshu Kumar Upadhyay
Definitions
• “Pattern” as the name suggests,
means series of events occurring in a
definite order.
• Design patterns are just convenient
ways of reusing object-oriented code
between projects and between
programmers. The idea behind
design patterns is simple-- write
down and catalog common
interactions between objects that
Pattern Categories
There are 23 design patterns in
Java. These patterns are grouped
under three heads:
1. Creational Patterns
2. Structural Patterns
3. Behavioral Patterns
Creational Pattern
All the creational patterns define
the best possible way in which an
object can be instantiated. These
describes the best way to CREATE
object instances. Now everyone
knows the object instance in Java can
be created using a new operator.
Type Of Creational Patterns
There are five type of creational
patterns

Factory Pattern
Abstract Factory Pattern
Builder Pattern
Prototype Pattern
Singleton Pattern
Factory Pattern
The Problem: One of the goals of object-oriented
design is to delegate responsibility among different
objects. This kind of partitioning is good since it
encourages Encapsulation and Delegation.
• Sometimes, an Application (or framework) at runtime,
cannot anticipate the class of object that it must
create. The Application (or framework) may know that
it has to instantiate classes, but it may only know
about abstract classes (or interfaces), which it cannot
instantiate. Thus the Application class may only know
when it has to instantiate a new Object of a class, not
what kind of subclass to create.
• a class may want it's subclasses to specify the objects
to be created.
• a class may delegate responsibility to one of several
helper subclasses so that knowledge can be localized
Factory Pattern (cont…)

Definition: The essence of the Factory Pattern is to


"Define an interface for creating an object, but let the
subclasses decide which class to instantiate. The Factory
method lets a class defer instantiation to subclasses.“
If we have a super class and n sub-classes, and based
on data provided, we have to return the object of one of the
sub-classes, we use a factory pattern .
Factory methods are common in toolkits and
frameworks where library code needs to create objects of
types which may be subclasses by applications using the
framework.
The BorderFactory class in java used combination of
Factory and Singleton pattern
Abstract Factory Pattern
A software design pattern, the Abstract Factory
Pattern provides a way to encapsulate a group of
individual factories that have a common theme.
In normal usage, the client software would create a
concrete implementation of the abstract factory and then
use the generic interfaces to create the concrete objects
that are part of the theme. The client does not know (or
care) about which concrete objects it gets from each of
these internal factories since it uses only the generic
interfaces of their products. This pattern separates the
details of implementation of a set of objects from its
general usage.

The Abstract Factory pattern is one level of abstraction


higher than the factory pattern. You can use this pattern
when you want to return one of several related classes of
Abstract Factory Pattern
(cont…)
• In Java the pluggable look-and-feel classes accomplish this
at the system level so that instances of the visual interface
components are returned correctly once the type of look-
and-feel is selected by the program. Here we find the name
of the current windowing system and then tell the PLAF
abstract factory to generate the correct objects for us.
String laf = UIManager.getSystemLookAndFeelClassName();
try {
UIManager.setLookAndFeel(laf);
}
catch (UnsupportedLookAndFeelException exc){
System.err.println("UnsupportedL&F: " + laf);
}
catch (Exception exc){
System.err.println("Error loading " + laf);
}
Builder Pattern
“The Builder Pattern separates the construction of a
complex object from its representation so that the same
construction process can create different representations”.
The Builder Pattern consists of a Builder,
ConcreteBuilder, Director and Product.
The Director object is responsible for the
construction process of the complex object but delegates
the actual creation and assembly to the Builder interface.
The Builder object specifies the interface for
creating parts of the complex object.
The Product represents the complex object that is
created by the ConcreteBuilder objects. The Product
consists of multiple parts that are created separately by the
ConcreteBuilder objects.
The ConcreteBuilder objects create and assemble
the parts that make up the Product through the Builder
interface.
Builder Pattern (cont….)
Prototype Pattern
A prototype pattern is a used when the type of objects
to create is determined by a prototypical instance, which is
cloned to produce new objects.

To implement the pattern, declare an abstract base


class that specifies a pure virtual clone() method. Any class
that needs a "polymorphic constructor" capability derives
itself from the abstract base class, and implements the
clone() operation.

Cloning In Java:
Prototype Pattern (cont…)
Singleton Pattern
“Ensure a class only has one instance, and provide a
global point of access to it.”

The Singleton Pattern can be implemented in Java in


one of several ways.
Creating Singleton Pattern by
Using Static Variable
Static Class
Using Static Method
Singleton Pattern (cont…)

By Static Variable: In this approach, we create a static


variable which is used to maintain the single instance of class.

class PrintSpooler
{
static boolean instance_flag = false; //true if 1 instance
public PrintSpooler() throws Singleton Exception
{
if (instance_flag)
throw new SingletonException("Only one spooler
allowed");
else
instance_flag = true; //set flag for 1 instance
System.out.println("spooler opened");
}
public void finalize()
{
instance_flag = false; //clear if destroyed
}
Singleton Pattern (cont…)

By Static Class: In this approach, all methods and


fields of the class is declared static. There already is a kind
of Singleton class in the standard Java class libraries: the
Math class. This is a class that is declared final and all
methods are declared static.

One advantage of the final class approach is that you


don’t have to
wrap things in awkward try blocks. The disadvantage is
that if you would like to drop the restrictions of Singleton
status, this is easier to do in the exception style class
structure. We’d have a lot of reprogramming to do to make
the static approach allow multiple instances.
Singleton Pattern (cont…)

By Static Method: In this approach, we make the


constructor private so an instance can be created from within
static method of the class. It’s overcome both of the problems
which is mentioned in previous approaches.

class PrintSpooler
{
static PrintSpooler printSpooler;
private PrintSpooler()
{
// ----------
}
public PrintSpooler getSpoolerInstance()
{
if(printSpooler == null)
{
printSpooler = new PrintSpooler();
}
Structural Pattern
Structural patterns describe how classes and
objects can be combined to form larger
structures. The difference between class patterns
and object patterns is that class patterns describe
how inheritance can be used to provide more
useful program interfaces. Object patterns, on the
other hand, describe how objects can be
composed into larger structures using object
composition, or the inclusion of objects within
other objects.
Type of Structural Patterns
There are seven type of Structural
patterns

Adapter Pattern
Bridge Pattern
Composite Pattern
Decorator Pattern
Facade Pattern
Flyweight Pattern
Proxy Pattern
Adapter Pattern
“This pattern establishes a relationship between the
two unrelated interfaces such that they work together. This
is similar to the conversion of one interface of one class to
the interface expected by the client.”

An adapter allows classes to work together that


normally could not because of incompatible interfaces, by
providing its interface to clients while using the original
interface. The adapter translates calls to its interface into
calls to the original interface, and the amount of code
necessary to do this is typically small. The adapter is also
responsible for transforming data into appropriate forms.
For instance, if multiple boolean values are stored as a
single integer but your consumer requires a 'true'/'false',
Bridge Pattern
The bridge pattern is used in software engineering
which is meant to "decouple an abstraction from its
implementation so that the two can vary independently“.
The bridge uses encapsulation, aggregation, and can use
inheritance to separate responsibilities into different
classes.

When a class varies often, the features of object-


oriented programming become very useful because
changes to a program's code can be made easily with
minimal prior knowledge about the program. The bridge
pattern is useful when both the class as well as what it does
varies. The class itself can be thought of as the
implementation and what the class can do as the
abstraction. The bridge pattern can also be thought of as
Composite Pattern
Composite allows a group of objects to be treated in the
same way as a single instance of an object. The intent of
composite is to "compose" objects into tree structures to
represent part-whole hierarchies. Composite lets clients
treat individual objects and compositions uniformly.

Composite can be used when clients should ignore the


difference between compositions of objects and individual
objects. If programmers find that they are using multiple
objects in the same way, and often have nearly identical
code to handle each of them, then composite is a good
choice; it is less complex in this situation to treat primitives
and composites as homogeneous.
Decorator Pattern
“The decorator pattern is a design pattern that allows
new/additional behaviour to be added to an existing class
dynamically” .
The Decorator pattern provides us with a way to modify
the behavior of individual objects without having to create a
new derived class. Suppose we have a program that uses
eight objects, but three of them need an additional feature.
You could create a derived class for each of these objects,
and in many cases this would be a perfectly acceptable
solution. However, if each of these three objects require
different modifications, this would mean creating three
derived classes. Further, if one of the classes has features
of both of the other classes, you begin to create a
complexity that is both confusing and unnecessary.
Facade Pattern
A facade is an object that provides a simplified interface
to a larger body of code, such as a class library.

A facade can:
– make a software library easier to use and understand, since
the facade has convenient methods for common tasks;
– make code that uses the library more readable, for the same
reason;
– reduce dependencies of outside code on the inner workings of
a library, since most code uses the facade, thus allowing more
flexibility in developing the system
– wrap a poorly-designed collection of APIs with a single well-
designed API.
An Adapter is used when the wrapper must respect a
particular interface and must support a polymorphic
behavior. On the other hand a facade is used when one
Facade Pattern
Flyweight Pattern
• There are cases in programming where it seems that you
need to generate a very large number of small class
instances to represent data. Sometimes you can greatly
reduce the number of different classes that you need to
instantiate if you can recognize that the instances are
fundamentally the same except for a few parameters. If you
can move those variables outside the class instance and
pass them in as part of a method call, the number of
separate instances can be greatly reduced.
Proxy Pattern
“A proxy is a class functioning as an interface to
something else. The proxy could interface to anything: a
network connection, a large object in memory, a file, or
some other resource that is expensive or impossible to
duplicate.”

• In situations where multiple copies of a complex object


must exist the proxy pattern can be adapted to incorporate
the flyweight pattern in order to reduce the application's
memory footprint. Typically one instance of the complex
object is created, and multiple proxy objects are created, all
of which contain a reference to the single original complex
object. Any operations performed on the proxies are
forwarded to the original object. Once all instances of the
proxy are out of scope, the complex object's memory may
Behavioral Pattern
“Behavioral design patterns are design
patterns that identify common communication
patterns between objects and realize these
patterns. By doing so, these patterns increase
flexibility in carrying out this communication”

The most common Behavioral Pattern are as follows:


1. Chain of Responsibility Pattern
2. Command Pattern
3. Interpreter Pattern
4. Iterator Pattern
5. Mediator Pattern
Behavioral Pattern (Cont…)

6. Memento Pattern
7. Observer Pattern
8. State Pattern
9. Strategy Pattern
10. Template Pattern
11. Visitor Pattern
Chain Of Responsibility
“The Chain Of Responsibility pattern allows a
number of classes to attempt to handle a request,
without any of them knowing about the
capabilities and functionalities of other classes. It
provides a loose coupling between these classes;
The only common link is the request that is
passed between them. The request is passed
along until one of classes can handle it”.

Applicability:
4. You have more than one handler that can handle a request
and there is no way to know which handler to use. The
handler must be determined by chain.
Chain Of Responsibility
(Cont…)
2. You want to issue a request to one of several objects
without specifying which one explicitly.
3. You want to be able to modify the set of object dynamically
that can handle request.

Example: the best example of the “Chain Of Responsibility”


pattern is “Multiple catch statement” to handle a
exception.
Command Pattern
“The command pattern is a design pattern in
which an object is used to represent and
encapsulate all the information needed to call a
method at a later time. This information includes
the method name, the object that owns the
method and values for the method parameters”.
Three terms always associated with the command pattern
are client, invoker and receiver. The client instantiates the
command object and provides the information required to call
the method at a later time. The invoker decides when the
method should be called. The receiver is an instance of the
class that contains the method's code.
This pattern is different from the Chain of Responsibility
in a way that, in the earlier one, the request passes through
each of the classes before finding an object that can take
the responsibility. The command pattern however finds the
Interpreter Pattern
“The interpreter pattern is a particular design
pattern. The interpreter pattern specifies how to
evaluate sentences in a language. The basic idea
is to have a class for each symbol (terminal or
nonterminal) in a specialized computer language.
The syntax tree of a sentence in the language is
an instance of the composite pattern and is used
to evaluate (interpret) the sentence”.
To make this interpreter clearer, let’s take an example.
The “musical notes” is an “Interpreted Language”. The
musicians read the notes, interpret them according to “Sa,
Re, Ga, Ma…” or “Do, Re, Me… ” etc and play the
instruments, what we get in output is musical sound waves.
Think of a program which can take the Sa, Re, Ga, Ma etc
and produce the sounds for the frequencies.
For Sa, the frequency is 256 Hz, similarly, for Re, it is 288Hz
and for Ga, it is 320 Hz etc etc…
Iterator Pattern
“The iterator is one of the simplest and most
frequently used design pattern. The iterator
pattern move you through a list or collection of
data using standard interface without having to
know the detail of internal representation of the
data. In addition you can define special iterator
that perform some special processing and return
only specific element of data collection.

We use iterators quite frequently in everyday life. For


example, remote control of TV. Any remote control we use,
either at home/hotel or at a friend’s place, we just pick up
the TV remote control and start pressing Up and Down or
Forward and Back keys to iterate through the channels.
Mediator Pattern
Usually a program is made up of a (sometimes
large) number of classes. So the logic and
computation is distributed among these classes.
However, as more classes are developed in a
program, especially during maintenance and/or
refactoring, the problem of communication
between these classes may become more
complex. This makes the program harder to read
and maintain. Furthermore, it can become
difficult to change the program, since any change
may affect code in several other classes.
With the mediator pattern communication
between objects is encapsulated with a mediator
object. Objects no longer communicate directly
with each other, but instead communicate
through the mediator. This reduces the
Mediator Pattern (Cont…)

A very common example can be airplanes interacting


with the control tower and not among themselves. The
control tower knows exactly, where each of the airplanes is,
and guides them whereas the airplanes have their own
responsibilities of landing and takeoff. Another popular
example is Stock exchange, The stock exchange acting like
a mediator and the traders did not need to know other
traders and services provided by them to make a deal. The
traders have their own responsibilities as buyers and sellers
and it was stock exchange’s responsibility to match their
deals and get the settlement done.
Memento Pattern
“The memento pattern is a software design
pattern that provides the ability to restore an
object to its previous stat”

This pattern has three roles for objects.


4. The Originator is the object whose state we wants to
save.
5. The memento is another object that save the state of
originator.
6. The care taker manages the timing of saving of the state,
saves the memento and, if needed, uses the memento to
restore the state of the originator.
Observer Pattern
“The observer is a software design pattern in
which an object, called the subject, maintains a
list of its dependents, called observers, and
notifies them automatically of any state changes,
usually by calling one of their methods. It is
mainly used to implement distributed event
handling systems.”

For Example: You might represent stock price changes


both in a graph and in a table or list box. Each time the
price changes, we did expect both the representations to
change at once without any action in our parts.

Java API provides a built-in interface Observer and


State
“The State pattern is used when you want to
have an enclosing class switch between number
of related contained classes, and pass method
call to the current contained class. The state
pattern switches between internal classes in such
a way that enclosing object appears to changes
its class.”

Many programmer have had the experience of


creating a class which perform slightly different calculations
or display different information based into argument passed
into the class. This frequently leads to sort of switch or if-
else statement inside the class that determine which
behavior to carry out. It is inelegance that the state pattern
Strategy Pattern
“Define a family of algorithms, encapsulate
each one, and make them interchangeable. [The]
Strategy [pattern] lets the algorithm vary
independently from clients that use it.”

The strategy pattern is useful for situations where it is


necessary to dynamically swap the algorithms used in an
application. The strategy pattern is intended to provide a
means to define a family of algorithms, encapsulate each
one as an object, and make them interchangeable. The
strategy pattern lets the algorithms vary independently
from clients that use them.
Template Patten
“Whenever you write a parent class where you
leave one or more of the methods to be
implemented by the derived classes, You are in
essence using The Template Pattern. The
template pattern formalizes the idea of defining
an algorithm in a class, but leaving some of the
details to be implemented in subclasses. In other
words, If your base class is an abstract class, You
are using the simple form of the Template
Pattern.”

In a template pattern, the model has no inherent


knowledge of how it would be utilized. The actual algorithm
is delegated to the views, i.e. templates. Different
Visitor Pattern
“The visitor design pattern is a way of
separating an algorithm from an object structure
upon which it operates. A practical result of this
separation is the ability to add new operations to
existing object structures without modifying those
structures. Thus, using the visitor pattern helps
conformance with the open/closed principle.”
In essence, the visitor allows one to add new virtual
functions to a family of classes without modifying the
classes themselves; instead, one creates a visitor class that
implements all of the appropriate specializations of the
virtual function. The visitor takes the instance reference as
input, and implements the goal through double dispatch.

You might also like