3. 3
Overview
In 1994, Design Patterns: Elements of Reusable Object-
Oriented Software by Erich Gamma, Richard Helm, Ralph
Johnson and John Vlissides explained the usefulness of
patterns and resulted in the widespread popularity of design
patterns.
These four authors together are referred to as the Gang of
Four (GoF).
In this book, the authors documented the 23 patterns they
found in their respective works.
4. 4
Definitions
• Design patterns are solutions to software design
problems you find again and again in real-world
application development
• Design patterns are standard solutions to common
problems in software design
5. 5
Design Pattern Catalog
CREATIONAL
PATTERNS
1. Factory Method
2. Abstract Factory
3. Builder
4. Prototype
5. Singleton
STRUCTURAL
PATTERNS
1. Adapter
2. Bridge
3. Composite
4. Decorator
5. Façade
6. Flyweight
7. Proxy
BEHAVIORAL
PATTERNS
1. Chain of Responsibility
2. Command
3. Interpreter
4. Iterator
5. Mediator
6. Memento
7. Observer
8. State
9. Strategy
10. Template Method
11. Visitor
Above categories are based on Gang of Four Book. There are
more categories based on programming principles(SOLID, DRY,
etc).
6. 6
Singleton
Definition
• Ensures a class has only one instance and provide a global point of
access to it
Problem & Context
• Sometimes there may be a need to have one and only one instance
of a given class during the lifetime of an application.
Solution
• Create a class with a method that creates a new instance of the
object if one does not exist. If one does exist, it returns a reference to
the object that already exists. To make sure that the object cannot be
instantiated any other way, the constructor is made either private
Example:
Implementations like Logger, Configuration Provider, Factory, Printer
and many more follow Singleton Pattern.
7. Singleton Example
public class Singleton {
private static Singleton singleton = new Singleton( );
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton(){ }
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
7
8. Singleton Lazy Instantiation
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
8
9. Singleton -Lazy Inst. More Robust
9
//Lazy instantiation using double locking mechanism.
class Singleton
{
private static Singleton instance;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null){
System.out.println("getInstance(): First time getInstance was invoked!");
instance = new Singleton();
}
}
}
return instance;
}
}
10. 10
Factory
Overview
• Factory pattern is one of most used design pattern in Java. This type
of design pattern comes under creational pattern as this pattern
provides one of the best ways to create an object.
• In Factory pattern, we create object without exposing the creation
logic to the client and refer to newly created object using a common
interface.
Problem & Context
• If an object needs to know the selection criteria to instantiate an
appropriate class, this results in a high degree of coupling. Whenever
the selection criteria change, every object that uses the class must be
changed correspondingly
11. Factory Example
11
public class ShapeFactory {
//use getShape method to get object of type shape
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
12. Examples of Factory pattern in Java
12
• JDBC database access is based around the Factory pattern.
With JDBC, javax.sql.DataSource is the Factory object
and java.sql.Connection is the factory's generated object
• HibernateSessionFactory
• Many other third party libs like a reporting library called
Jasper will have FormatFactory that creates date format
based on timezone, pattern and locale
13. 13
Abstract Factory
Definition/Overview
• Provides an interface for creating families of related or dependent
objects without specifying their concrete classes
• In simple terms , Abstract Factory can create Factory object
Abstract Factory Implementation in JDK
• javax.xml.parsers.DocumentBuilderFactory#newInstance()
DocumentBuilderFactory docBuilderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder =
docBuilderFactory.newDocumentBuilder();
• javax.xml.transform.TransformerFactory#newInstance()
• javax.xml.xpath.XPathFactory#newInstance()
14. Factory Method
• The Factory Method defines an interface for creating
objects, but lets subclasses decide which classes to
instantiate. Injection molding presses demonstrate this
pattern. Manufacturers of plastic toys process plastic
molding powder, and inject the plastic into molds of the
desired shapes. The class of toy (car, action figure, etc.)
is determined by the mold.
• Factory method in JDK : The method named iterator() in
each collection class return appropriate Iterator
implementations.
14
16. Data Access Object Pattern
• Data Access Object Pattern or DAO pattern is used to separate low
level data accessing API or operations from high level business
services. Following are the participants in Data Access Object
Pattern.
• Data Access Object Interface - This interface defines the standard
operations to be performed on a model object(s).
• Data Access Object concrete class - This class implements above
interface. This class is responsible to get data from a data source
which can be database / xml or any other storage mechanism.
• Model Object or Value Object - This object is simple POJO
containing get/set methods to store data retrieved using DAO class.
16
17. DAO Pattern Example
17
Inteface
import java.util.List;
public interface StudentDao {
public List<Student> getAllStudents();
public Student getStudent(int rollNo);
public void updateStudent(Student student);
public void deleteStudent(Student student);
}
Usage :
StudentDao studentDao = new StudentDaoImpl();
//update student
Student student =studentDao.getAllStudents().get(0);
student.setName("Michael");
studentDao.updateStudent(student);
//get the student
studentDao.getStudent(0);
StudentDao studentDao = new StudentDaoImpl();
18. DAO Examples
• Data Access Objects (DAOs), making use of the
Hibernate implementation for the Java Persistence API
(JPA) specification.
• Hibernate provides implementation methods for CRUD
operations.
18
20. MVC Examples
• MVC architecture is implemented by various frameworks.
Most popular are Struts and Spring
20
21. 21
Façade
• The facade pattern (or façade pattern) is a software design pattern
commonly used with object-oriented programming. The name is by
analogy to an architectural facade.
• A facade is an object that provides a simplified interface to a larger
body of code, such as a class library. A facade can:
1. Make a software library easier to use, understand and test, since
the facade has convenient methods for common tasks;
2.Make the library more readable, for the same reason;
3. 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;
4. Wrap a poorly designed collection of APIs with a single well-
designed API (as per task needs).
24. J2EE Façade Example contd..
• For example, for a banking application, you may group
the interactions related to managing an account into a
single facade. The use cases Create New Account,
Change Account Information, View Account information,
and so on all deal with the coarse-grained entity object
Account. Creating a session bean facade for each use
case is not recommended. Thus, the functions required to
support these related use cases could be grouped into a
single Session Facade called AccountSessionFacade
24
25. 25
Benefits & Drawbacks
Benefits:
• Design patterns enable large-scale reuse of software architectures
• Patterns explicitly capture expert knowledge and design tradeoffs,
and make this expertise more widely available
• Patterns help improve developer communication
Drawbacks:
• Patterns may not lead to direct code reuse
• Patterns are deceptively simple
• Teams may suffer from pattern overload
• Patterns are validated by experience and discussion rather than by
automated testing
26. 26
References
• Design Patterns: Elements of Reusable Object-Oriented Software" by
Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides
• Design Pattern-Head First
• Software Architecture Design Patterns in Java
By: Partha Kutchana
• The Design Patterns Java Companion
By: James W. Cooper
• http://en.wikipedia.org/wiki/Software_design_pattern
These 23 Patterns will be the focus of the presentation.
The objective of this presentation is for you to be able to identify all the GOF Design Patterns and learn when to apply some of them.
Not all patterns can be applied in certain situations because many of the patterns cannot be applied in a single software application.
It takes experience and extensive exposure to applications before you can appreciate all the patterns.
Several definitions are given here to provide a more comprehensive treatment.
Please take note of these keywords: recurring, standard, common, solution, problem, multiple, context.
Creational Patterns deal with initializing and configuring classes and objects.
Structural Patterns deal with decoupling interface and implementation of classes and objects.
Behavioral Patterns deal with dynamic interactions among classes and objects.
There are other design patterns in existence but these are the most common
Frequency of use: High (5 of 5)
Sample Application:
Consider a LoadBalancing object. Only a single instance (the singleton) of the class can be created because servers may dynamically come on- or off-line and every request must go through the one object that has knowledge about the state of the (web) farm.
A single database connection object in an application
Frequency of use: Medium high (4 of 5)
Sample Application:
Creating different documents (e.g., Report, Resume, etc…) from a base Document class.
Frequency of use: Medium high (4 of 5)
Sample Application:
Creation of different animal worlds from different Continents for a computer game using different factories. Although the animals created by the Continent factories are different, the interactions among the animals remain the same.
Frequency of use: High (5 of 5)
Sample application:
A mortgage application object which provides a simplified interface to a large subsystem of classes (e.g., Bank, Credit, Loan) measuring the creditworthiness of an applicant
Font & Graphics from the Java API are façade classes for parsing font files and rendering text into pixels.
The classes and/or objects participating in the Façade pattern are:
Facade (MortgageApplication)
Knows which subsystem classes are responsible for a request
Delegates client requests to appropriate subsystem objects
Subsystem classes (Bank, Credit, Loan)
Implement subsystem functionality
Handle work assigned by the Facade object
Have no knowledge of the facade and keep no reference to it