Java Design Patterns
Java Design Patterns
#Factory Pattern
Factory design pattern is used when we have a super class with multiple sub-classes and
based on input,
we need to return one of the sub-class. This pattern take out the responsibility of
instantiation of a
class from client program to the factory class. We can apply Singleton pattern on Factory
class or make the factory
method static. This is one of the most widely used java design pattern.
In Abstract Factory pattern, we get rid of if-else block and have a factory class for each
sub-class and then an Abstract Factory class that will return the sub-class based on the
input factory class. Check out Abstract Factory Pattern to know how to implement this
pattern with example program.
#Builder Pattern
This pattern was introduced to solve some of the problems with Factory and Abstract
Factory design patterns when the Object contains a lot of attributes. Builder pattern
solves the issue with large number of optional parameters and inconsistent state by
providing a way to build the object step-by-step and provide a method that will actually
return the final Object. Check out Builder Pattern for example program and classes used
in JDK.
#Prototype Pattern
Prototype pattern is used when the Object creation is a costly affair and requires a lot of
time and resources and you have a similar object already existing. So this pattern
provides a mechanism to copy the original object to a new object and then modify it
according to our needs. This pattern uses java cloning to copy the object.
Prototype design pattern mandates that the Object which you are copying should provide
the copying feature. It should not be done by any other class. However whether to use
shallow or deep copy of the Object properties depends on the requirements and its a
design decision. Check out Prototype Pattern for sample program.
#Structural Design Patterns
Structural patterns provide different ways to create a class structure, for example using
inheritance and composition to create a large object from small objects.
#Adapter Pattern
Adapter design pattern is one of the structural design pattern and its used so that two
unrelated interfaces can work together. The object that joins these unrelated interface is
called an Adapter. As a real life example, we can think of a mobile charger as an adapter
because mobile battery needs 3 volts to charge but the normal socket produces either
120V (US) or 240V (India). So the mobile charger works as an adapter between mobile
charging socket and the wall socket. Check out Adapter Pattern for example program and
it’s usage in Java.
#Composite Pattern
Composite pattern is one of the Structural design pattern and is used when we have to
represent a part-whole hierarchy. When we need to create a structure in a way that the
objects in the structure has to be treated the same way, we can apply composite design
pattern.
Lets understand it with a real life example – A diagram is a structure that consists of
Objects such as Circle, Lines, Triangle etc and when we fill the drawing with color (say
Red), the same color also gets applied to the Objects in the drawing. Here drawing is
made up of different parts and they all have same operations. Check out Composite
Pattern article for different component of composite pattern and example program.
#Proxy Pattern
Proxy pattern intent is to “Provide a surrogate or placeholder for another object to control
access to it”. The definition itself is very clear and proxy pattern is used when we want to
provide controlled access of a functionality.
Let’s say we have a class that can run some command on the system. Now if we are
using it, its fine but if we want to give this program to a client application, it can have
severe issues because client program can issue command to delete some system files or
change some settings that you don’t want. Check out Proxy Pattern post for the example
program with implementation details.
#Flyweight Pattern
Flyweight design pattern is used when we need to create a lot of Objects of a class. Since
every object consumes memory space that can be crucial for low memory devices, such
as mobile devices or embedded systems, flyweight design pattern can be applied to
reduce the load on memory by sharing objects. String Pool implementation in java is one
of the best example of Flyweight pattern implementation. Check out Flyweight Pattern
article for sample program and implementation process.
#Facade Pattern
Facade Pattern is used to help client applications to easily interact with the system.
Suppose we have an application with set of interfaces to use MySql/Oracle database and
to generate different types of reports, such as HTML report, PDF report etc. So we will
have different set of interfaces to work with different types of database. Now a client
application can use these interfaces to get the required database connection and
generate reports. But when the complexity increases or the interface behavior names are
confusing, client application will find it difficult to manage it. So we can apply Facade
pattern here and provide a wrapper interface on top of the existing interface to help
client application. Check out Facade Pattern post for implementation details and sample
program.
#Bridge Pattern
When we have interface hierarchies in both interfaces as well as implementations, then
bridge design pattern is used to decouple the interfaces from implementation and hiding
the implementation details from the client programs. Like Adapter pattern, its one of the
Structural design pattern.
The implementation of bridge design pattern follows the notion to prefer Composition
over inheritance. Check out Bridge Pattern post for implementation details and sample
program.
#Decorator Pattern
Decorator design pattern is used to modify the functionality of an object at runtime. At
the same time other instances of the same class will not be affected by this, so individual
object gets the modified behavior. Decorator design pattern is one of the structural
design pattern (such as Adapter Pattern, Bridge Pattern, Composite Pattern) and uses
abstract classes or interface with composition to implement.
We use inheritance or composition to extend the behavior of an object but this is done at
compile time and its applicable to all the instances of the class. We can’t add any new
functionality of remove any existing behavior at runtime – this is when Decorator pattern
comes into picture. Check out Decorator Pattern post for sample program and
implementation details.
Air traffic controller is a great example of mediator pattern where the airport control room
works as a mediator for communication between different flights. Mediator works as a
router between objects and it can have it’s own logic to provide way of communication.
Check out Mediator Pattern post for implementation details with example program.
We know that we can have multiple catch blocks in a try-catch block code. Here every
catch block is kind of a processor to process that particular exception. So when any
exception occurs in the try block, its send to the first catch block to process. If the catch
block is not able to process it, it forwards the request to next object in chain i.e next
catch block. If even the last catch block is not able to process it, the exception is thrown
outside of the chain to the calling program.
ATM dispense machine logic can be implemented using Chain of Responsibility Pattern,
check out the linked post.
#Observer Pattern
Observer design pattern is useful when you are interested in the state of an object and
want to get notified whenever there is any change. In observer pattern, the object that
watch on the state of another object are called Observer and the object that is being
watched is called Subject.
Java Message Service (JMS) uses Observer pattern along with Mediator pattern to allow
applications to subscribe and publish data to other applications. Check out Observer
Pattern post for implementation details and example program.
#Strategy Pattern
Strategy pattern is used when we have multiple algorithm for a specific task and client
decides the actual implementation to be used at runtime.
Strategy pattern is also known as Policy Pattern. We defines multiple algorithms and let
client application pass the algorithm to be used as a parameter. One of the best example
of this pattern is Collections.sort() method that takes Comparator parameter. Based on
the different implementations of Comparator interfaces, the Objects are getting sorted in
different ways.
Check out Strategy Pattern post for implementation details and example program.
#Command Pattern
Command Pattern is used to implement lose coupling in a request-response model. In
command pattern, the request is send to the invoker and invoker pass it to the
encapsulated command object. Command object passes the request to the appropriate
method of Receiver to perform the specific action.
Let’s say we want to provide a File System utility with methods to open, write and close
file and it should support multiple operating systems such as Windows and Unix.
To implement our File System utility, first of all we need to create the receiver classes that
will actually do all the work. Since we code in terms of java interfaces, we can have
FileSystemReceiver interface and it’s implementation classes for different operating
system flavors such as Windows, Unix, Solaris etc. Check out Command Pattern post for
the implementation details with example program.
#State Pattern
State design pattern is used when an Object change it’s behavior based on it’s internal
state.
If we have to change the behavior of an object based on it’s state, we can have a state
variable in the Object and use if-else condition block to perform different actions based on
the state. State pattern is used to provide a systematic and lose-coupled way to achieve
this through Context and State implementations.
Check out State Pattern post for implementation details with example program.
#Visitor Pattern
Visitor pattern is used when we have to perform an operation on a group of similar kind of
Objects. With the help of visitor pattern, we can move the operational logic from the
objects to another class.
For example, think of a Shopping cart where we can add different type of items
(Elements), when we click on checkout button, it calculates the total amount to be paid.
Now we can have the calculation logic in item classes or we can move out this logic to
another class using visitor pattern. Let’s implement this in our example of visitor pattern.
Check out Visitor Pattern post for implementation details.
#Interpreter Pattern
is used to defines a grammatical representation for a language and provides an
interpreter to deal with this grammar.
The best example of this pattern is java compiler that interprets the java source code into
byte code that is understandable by JVM. Google Translator is also an example of
interpreter pattern where the input can be in any language and we can get the output
interpreted in another language.
#Iterator Pattern
Iterator pattern in one of the behavioral pattern and it’s used to provide a standard way
to traverse through a group of Objects. Iterator pattern is widely used in Java Collection
Framework where Iterator interface provides methods for traversing through a collection.
Iterator pattern is not only about traversing through a collection, we can provide different
kind of iterators based on our requirements. Iterator pattern hides the actual
implementation of traversal through the collection and client programs just use iterator
methods. Check out Iterator Pattern post for example program and implementation
details.
#Memento Pattern
Memento design pattern is used when we want to save the state of an object so that we
can restore later on. Memento pattern is used to implement this in such a way that the
saved state data of the object is not accessible outside of the object, this protects the
integrity of saved state data.
Memento pattern is implemented with two objects – Originator and Caretaker. Originator
is the object whose state needs to be saved and restored and it uses an inner class to
save the state of Object. The inner class is called Memento and its private, so that it can’t
be accessed from other objects.
Check out Memento Pattern for sample program and implementation details.
That’s all for different design patterns in java, this post intent is to provide an index to
browse all of them easily.
-------------------
-------------------------
---------------------------
import java.util.ArrayList;
import java.util.List;
@Override
public void registerObserver(IObserver o) {
listOfObservers.add(o);
}
@Override
public void removeObserver(IObserver o) {
listOfObservers.remove(o);
}
@Override
public void notifyObserver() {
if (available == true) {
notifyObserver();
}
}
-----------------------------------------
cus1.setCustomerName("Dinesh");
cus2.setCustomerName("Vijay");
iphone6.registerObserver(cus1);
iphone6.registerObserver(cus2);
try {
int i = 0;
while (i < 3) {
System.out.println("Waiting..");
Thread.sleep(1000);
++i;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
iphone6.setAvailable(true);
-------------
Output:
__________________________________________________________________________________________
_________________________________________________
2. SINGLETON
This is the most used pattern. A lot of framework already implement this pattern, such as
Spring, CDI (via @ApplicationScoped) or EJBs (using @Singleton). Still, it is nice to know
how to implement it the old way. ;)
private SingletonSample() {
}
This pattern is much like the Singleton, but the Initialization on Demand Holder has
critical advantage over the Singleton: It is thread safe.
The getInstance() method from the Singleton pattern is not thread safe, not if you don't
make it synchronized, so, it can be instantiate more than once. If you do make your
method synchronized, you are making your getInstance() method slower than it could be
if it were not.
__________________________________________________________________________________________
_________________________________________________
Both are well-known design patterns. For sure two of the most useful design patterns,
specially using them together.
When both are combined, you can create objects from a given qualifier. The example is
right below:
__________________________________________________________________________________________
_________________________________________________
4. FLUENT BUILDER
Some objects require lots of parameters to be created. In this case, either using the
constructor to create this object or using the setters will make our code ugly and hard to
understand.
private Builder() {
}
__________________________________________________________________________________________
_________________________________________________
5. CHAIN OF RESPONSIBILITY
You always need to build applications which require a lot of business logic. Behind this
much of logic, there is always high complexity. This high complexity makes our code
harder to understand, as well as harder to track, to log and so on.
The CoR pattern makes us break our code into little pieces and organize them into
sequential steps.
6. TEMPLATE METHOD
This pattern defines a skeleton in a method for an operation. It is very useful when your
have common method calls but different behaviors. This pattern is totally based in
polymorphism.
7. STATE PATTERN
A lot of objects have states. For example, a radio. A radio have basically two states: on
and off. Can we represent this in object oriented programming? Well, yes:
__________________________________________________________________________________________
_________________________________________________
8. Callback Pattern:
# Synchronous Callback:
The code execution will block or wait for the event before continuing.
Until your event returns a response your program will not execute any further.
So Basically the callback performs all its work before returning to the call statement.
The problem with synchronous callback is that they appear to lag.
# Asynchronous Callback:
An Asynchronous call do not block the program from the code execution.
when the call returns from the event the call returns back to the callback function.
So in the context of java we have to Create a new thread invoke the callback method
inside that thread.
Callback may be invoked from a thread but is not a requirement. A Callback may also
start a new thread
thus making themselves asynchronous.
package com.anurag.example.callback;
interface ClickHandler {
void onClick();
}
class Button {
// My Asynchronous task
//To make it Synchronous just remove new Thread Part.
public void click() {
// Driver Program
public static void main(String[] args) {
@Override
public void onClick() {
System.out.println("Button is clicked.");
}
});
btn.click();
__________________________________________________________________________________________
_________________________________________________
9. Prototype Design Pattern
Prototype design pattern is used when the Object creation is a costly affair and requires a
lot of time and resources and you have a similar
object already existing.
Prototype pattern provides a mechanism to copy the original object to a new object and
then modify it according to our needs.
Prototype design pattern uses java cloning to copy the object.
package com.anurag.example.prototype;
import java.util.ArrayList;
import java.util.List;
public Employees() {
empList = new ArrayList<String>();
}
// Notice that the clone method is overridden to provide a deep copy of the
// employees list.
@Override
public Object clone() throws CloneNotSupportedException {
List<String> temp = new ArrayList<String>();
for (String s : this.getEmpList()) {
temp.add(s);
}
return new Employees(temp);
}
---------
package com.anurag.example.prototype;
import java.util.List;
-----
If the object cloning was not provided, we will have to make database call to fetch the
employee list every time. Then do the manipulations that would have been resource and
time consuming.
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
10. Memento design pattern
Memento design pattern is one of the behavioral design pattern. Memento design pattern
is used when we want to save the state of an
object so that we can restore later on. Memento pattern is used to implement this in such
a
way that the saved state data of the object is not accessible outside of the object, this
protects the integrity of saved state data.
Memento design pattern is implemented with two objects – Originator and Caretaker.
Originator is the object whose state needs to be saved and restored and it uses an inner
class to save the state of Object. The inner class is called Memento and it’s private, so
that it can’t be accessed from other objects.
Caretaker is the helper class that is responsible for storing and restoring the Originator’s
state through Memento object.
Since Memento is private to Originator, Caretaker can’t access it and it’s stored as an
Object within the caretaker.
Memento Design Pattern Java
One of the best real life example is the text editors where we can save it’s data anytime
and use undo to restore it to previous saved state.
We will implement the same feature and provide a utility where we can write and save
contents to a File anytime and we
can restore it to last saved state. For simplicity, I will not use any IO operations to write
data into file.
Memento pattern is simple and easy to implement, one of the thing needs to take care is
that Memento class should be accessible
only to the Originator object. Also in client application, we should use caretaker object for
saving and restoring the originator state.
Also if Originator object has properties that are not immutable, we should use deep copy
or cloning to avoid data integrity issue like
I have used in above example. We can use Serialization to achieve memento pattern
implementation that is more generic rather than Memento
pattern where every object needs to have it’s own Memento class implementation.
One of the drawback is that if Originator object is very huge then Memento object size
will also be huge and use a lot of memory.
---------
package com.anurag.example.Memento;
---------
package com.anurag.example.Memento;
----------
package com.anurag.example.Memento;
@Override
public String toString() {
return this.content.toString();
}
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________
__________________________________________________________________________________________
_________________________________________________