SlideShare a Scribd company logo
1 of 27
Design Patterns
2
Contents
• Overview
• Definitions
• Design Pattern Catalog
• Design Patterns Descriptions
• Benefits & Drawbacks
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
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
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
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.
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
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
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
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
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;
}
}
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
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()
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
Factory Method Contd..
15
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
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();
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
MVC pattern
19
MVC Examples
• MVC architecture is implemented by various frameworks.
Most popular are Struts and Spring
20
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).
22
Façade Example
J2EE Façade Example
23
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
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
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
• Questions?
• Thanks
27

More Related Content

What's hot

Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...Raffi Khatchadourian
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern11prasoon
 
ORM Concepts and JPA 2.0 Specifications
ORM Concepts and JPA 2.0 SpecificationsORM Concepts and JPA 2.0 Specifications
ORM Concepts and JPA 2.0 SpecificationsAhmed Ramzy
 
Cleaner Code: How Clean Code is Functional Code
Cleaner Code: How Clean Code is Functional CodeCleaner Code: How Clean Code is Functional Code
Cleaner Code: How Clean Code is Functional CodeDave Fancher
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScriptLilia Sfaxi
 
Reflection in C Sharp
Reflection in C SharpReflection in C Sharp
Reflection in C SharpHarman Bajwa
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesecosio GmbH
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An IntroductionNguyen Cao
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate FrameworkRaveendra R
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objectsmcollison
 
Certification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxCertification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxRohit Radhakrishnan
 
.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath CommunityRohit Radhakrishnan
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Trainingsourabh aggarwal
 
Certification preparation - Error Handling and Troubleshooting recap.pptx
Certification preparation - Error Handling and Troubleshooting recap.pptxCertification preparation - Error Handling and Troubleshooting recap.pptx
Certification preparation - Error Handling and Troubleshooting recap.pptxRohit Radhakrishnan
 
Lecture08 computer applicationsie1_dratifshahzad
Lecture08 computer applicationsie1_dratifshahzadLecture08 computer applicationsie1_dratifshahzad
Lecture08 computer applicationsie1_dratifshahzadAtif Shahzad
 

What's hot (20)

Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
ORM Concepts and JPA 2.0 Specifications
ORM Concepts and JPA 2.0 SpecificationsORM Concepts and JPA 2.0 Specifications
ORM Concepts and JPA 2.0 Specifications
 
Cleaner Code: How Clean Code is Functional Code
Cleaner Code: How Clean Code is Functional CodeCleaner Code: How Clean Code is Functional Code
Cleaner Code: How Clean Code is Functional Code
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScript
 
Reflection in C Sharp
Reflection in C SharpReflection in C Sharp
Reflection in C Sharp
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An Introduction
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Data access
Data accessData access
Data access
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
Certification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxCertification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptx
 
.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Training
 
Certification preparation - Error Handling and Troubleshooting recap.pptx
Certification preparation - Error Handling and Troubleshooting recap.pptxCertification preparation - Error Handling and Troubleshooting recap.pptx
Certification preparation - Error Handling and Troubleshooting recap.pptx
 
Beyond pageobjects
Beyond pageobjectsBeyond pageobjects
Beyond pageobjects
 
Lecture08 computer applicationsie1_dratifshahzad
Lecture08 computer applicationsie1_dratifshahzadLecture08 computer applicationsie1_dratifshahzad
Lecture08 computer applicationsie1_dratifshahzad
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 

Viewers also liked

Adaptive processes advanced course in software design and architecture
Adaptive processes advanced course in software design and architectureAdaptive processes advanced course in software design and architecture
Adaptive processes advanced course in software design and architectureLN Mishra CBAP
 
Software Architecture Design Patterns
Software Architecture Design PatternsSoftware Architecture Design Patterns
Software Architecture Design PatternsStanislav
 
Transforming Software Architecture for the 21st Century (September 2009)
Transforming Software Architecture for the 21st Century (September 2009)Transforming Software Architecture for the 21st Century (September 2009)
Transforming Software Architecture for the 21st Century (September 2009)Dion Hinchcliffe
 
Software architecture and software design
Software architecture and software designSoftware architecture and software design
Software architecture and software designMr. Swapnil G. Thaware
 
Software Architecture Design for Begginers
Software Architecture Design for BegginersSoftware Architecture Design for Begginers
Software Architecture Design for BegginersChinh Ngo Nguyen
 
Nimble Framework - Software architecture and design in agile era - PSQT Template
Nimble Framework - Software architecture and design in agile era - PSQT TemplateNimble Framework - Software architecture and design in agile era - PSQT Template
Nimble Framework - Software architecture and design in agile era - PSQT Templatetjain
 
Software architecture & design patterns for MS CRM Developers
Software architecture & design patterns for MS CRM  Developers Software architecture & design patterns for MS CRM  Developers
Software architecture & design patterns for MS CRM Developers sebedatalabs
 
Software Architecture and Design - An Overview
Software Architecture and Design - An OverviewSoftware Architecture and Design - An Overview
Software Architecture and Design - An OverviewOliver Stadie
 
A Software Architect's View On Diagramming
A Software Architect's View On DiagrammingA Software Architect's View On Diagramming
A Software Architect's View On Diagrammingmeghantaylor
 

Viewers also liked (10)

Adaptive processes advanced course in software design and architecture
Adaptive processes advanced course in software design and architectureAdaptive processes advanced course in software design and architecture
Adaptive processes advanced course in software design and architecture
 
Agile Architecture
Agile ArchitectureAgile Architecture
Agile Architecture
 
Software Architecture Design Patterns
Software Architecture Design PatternsSoftware Architecture Design Patterns
Software Architecture Design Patterns
 
Transforming Software Architecture for the 21st Century (September 2009)
Transforming Software Architecture for the 21st Century (September 2009)Transforming Software Architecture for the 21st Century (September 2009)
Transforming Software Architecture for the 21st Century (September 2009)
 
Software architecture and software design
Software architecture and software designSoftware architecture and software design
Software architecture and software design
 
Software Architecture Design for Begginers
Software Architecture Design for BegginersSoftware Architecture Design for Begginers
Software Architecture Design for Begginers
 
Nimble Framework - Software architecture and design in agile era - PSQT Template
Nimble Framework - Software architecture and design in agile era - PSQT TemplateNimble Framework - Software architecture and design in agile era - PSQT Template
Nimble Framework - Software architecture and design in agile era - PSQT Template
 
Software architecture & design patterns for MS CRM Developers
Software architecture & design patterns for MS CRM  Developers Software architecture & design patterns for MS CRM  Developers
Software architecture & design patterns for MS CRM Developers
 
Software Architecture and Design - An Overview
Software Architecture and Design - An OverviewSoftware Architecture and Design - An Overview
Software Architecture and Design - An Overview
 
A Software Architect's View On Diagramming
A Software Architect's View On DiagrammingA Software Architect's View On Diagramming
A Software Architect's View On Diagramming
 

Similar to Introduction to design_patterns

Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design PatternsPham Huy Tung
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design PatternsSteven Smith
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsMohammad Shaker
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Steven Smith
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design PatternsLilia Sfaxi
 
C#.net, C Sharp.Net Online Training Course Content
C#.net, C Sharp.Net Online Training Course ContentC#.net, C Sharp.Net Online Training Course Content
C#.net, C Sharp.Net Online Training Course ContentSVRTechnologies
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Savio Sebastian
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objectsSandeep Chawla
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Arsen Gasparyan
 
Backbone.js
Backbone.jsBackbone.js
Backbone.jsVO Tho
 
Design Patterns
Design PatternsDesign Patterns
Design Patternsadil raja
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternNishith Shukla
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsLalit Kale
 
Mcknight well built extensions
Mcknight well built extensionsMcknight well built extensions
Mcknight well built extensionsRichard McKnight
 

Similar to Introduction to design_patterns (20)

Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design Patterns
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
C#.net, C Sharp.Net Online Training Course Content
C#.net, C Sharp.Net Online Training Course ContentC#.net, C Sharp.Net Online Training Course Content
C#.net, C Sharp.Net Online Training Course Content
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2
 
Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
Mcknight well built extensions
Mcknight well built extensionsMcknight well built extensions
Mcknight well built extensions
 

Recently uploaded

Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...
Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...
Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...babafaisel
 
Best VIP Call Girls Noida Sector 44 Call Me: 8448380779
Best VIP Call Girls Noida Sector 44 Call Me: 8448380779Best VIP Call Girls Noida Sector 44 Call Me: 8448380779
Best VIP Call Girls Noida Sector 44 Call Me: 8448380779Delhi Call girls
 
Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...
Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...
Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...Yantram Animation Studio Corporation
 
Cheap Rate ➥8448380779 ▻Call Girls In Huda City Centre Gurgaon
Cheap Rate ➥8448380779 ▻Call Girls In Huda City Centre GurgaonCheap Rate ➥8448380779 ▻Call Girls In Huda City Centre Gurgaon
Cheap Rate ➥8448380779 ▻Call Girls In Huda City Centre GurgaonDelhi Call girls
 
Recommendable # 971589162217 # philippine Young Call Girls in Dubai By Marina...
Recommendable # 971589162217 # philippine Young Call Girls in Dubai By Marina...Recommendable # 971589162217 # philippine Young Call Girls in Dubai By Marina...
Recommendable # 971589162217 # philippine Young Call Girls in Dubai By Marina...home
 
VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...
VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...
VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...Call Girls in Nagpur High Profile
 
Cheap Rate Call girls Kalkaji 9205541914 shot 1500 night
Cheap Rate Call girls Kalkaji 9205541914 shot 1500 nightCheap Rate Call girls Kalkaji 9205541914 shot 1500 night
Cheap Rate Call girls Kalkaji 9205541914 shot 1500 nightDelhi Call girls
 
Verified Trusted Call Girls Adugodi💘 9352852248 Good Looking standard Profil...
Verified Trusted Call Girls Adugodi💘 9352852248  Good Looking standard Profil...Verified Trusted Call Girls Adugodi💘 9352852248  Good Looking standard Profil...
Verified Trusted Call Girls Adugodi💘 9352852248 Good Looking standard Profil...kumaririma588
 
VIP Call Girls Service Mehdipatnam Hyderabad Call +91-8250192130
VIP Call Girls Service Mehdipatnam Hyderabad Call +91-8250192130VIP Call Girls Service Mehdipatnam Hyderabad Call +91-8250192130
VIP Call Girls Service Mehdipatnam Hyderabad Call +91-8250192130Suhani Kapoor
 
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service 🧵
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service  🧵CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service  🧵
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service 🧵anilsa9823
 
VIP College Call Girls Gorakhpur Bhavna 8250192130 Independent Escort Service...
VIP College Call Girls Gorakhpur Bhavna 8250192130 Independent Escort Service...VIP College Call Girls Gorakhpur Bhavna 8250192130 Independent Escort Service...
VIP College Call Girls Gorakhpur Bhavna 8250192130 Independent Escort Service...Suhani Kapoor
 
NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...
NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...
NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...Amil baba
 
SCRIP Lua HTTP PROGRACMACION PLC WECON CA
SCRIP Lua HTTP PROGRACMACION PLC  WECON CASCRIP Lua HTTP PROGRACMACION PLC  WECON CA
SCRIP Lua HTTP PROGRACMACION PLC WECON CANestorGamez6
 
CALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun serviceanilsa9823
 
Call Girls in Kalkaji Delhi 8264348440 call girls ❤️
Call Girls in Kalkaji Delhi 8264348440 call girls ❤️Call Girls in Kalkaji Delhi 8264348440 call girls ❤️
Call Girls in Kalkaji Delhi 8264348440 call girls ❤️soniya singh
 
WAEC Carpentry and Joinery Past Questions
WAEC Carpentry and Joinery Past QuestionsWAEC Carpentry and Joinery Past Questions
WAEC Carpentry and Joinery Past QuestionsCharles Obaleagbon
 
Fashion trends before and after covid.pptx
Fashion trends before and after covid.pptxFashion trends before and after covid.pptx
Fashion trends before and after covid.pptxVanshNarang19
 
Kurla Call Girls Pooja Nehwal📞 9892124323 ✅ Vashi Call Service Available Nea...
Kurla Call Girls Pooja Nehwal📞 9892124323 ✅  Vashi Call Service Available Nea...Kurla Call Girls Pooja Nehwal📞 9892124323 ✅  Vashi Call Service Available Nea...
Kurla Call Girls Pooja Nehwal📞 9892124323 ✅ Vashi Call Service Available Nea...Pooja Nehwal
 

Recently uploaded (20)

Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...
Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...
Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...
 
Best VIP Call Girls Noida Sector 44 Call Me: 8448380779
Best VIP Call Girls Noida Sector 44 Call Me: 8448380779Best VIP Call Girls Noida Sector 44 Call Me: 8448380779
Best VIP Call Girls Noida Sector 44 Call Me: 8448380779
 
Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...
Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...
Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...
 
Cheap Rate ➥8448380779 ▻Call Girls In Huda City Centre Gurgaon
Cheap Rate ➥8448380779 ▻Call Girls In Huda City Centre GurgaonCheap Rate ➥8448380779 ▻Call Girls In Huda City Centre Gurgaon
Cheap Rate ➥8448380779 ▻Call Girls In Huda City Centre Gurgaon
 
Recommendable # 971589162217 # philippine Young Call Girls in Dubai By Marina...
Recommendable # 971589162217 # philippine Young Call Girls in Dubai By Marina...Recommendable # 971589162217 # philippine Young Call Girls in Dubai By Marina...
Recommendable # 971589162217 # philippine Young Call Girls in Dubai By Marina...
 
VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...
VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...
VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...
 
Cheap Rate Call girls Kalkaji 9205541914 shot 1500 night
Cheap Rate Call girls Kalkaji 9205541914 shot 1500 nightCheap Rate Call girls Kalkaji 9205541914 shot 1500 night
Cheap Rate Call girls Kalkaji 9205541914 shot 1500 night
 
escort service sasti (*~Call Girls in Prasad Nagar Metro❤️9953056974
escort service sasti (*~Call Girls in Prasad Nagar Metro❤️9953056974escort service sasti (*~Call Girls in Prasad Nagar Metro❤️9953056974
escort service sasti (*~Call Girls in Prasad Nagar Metro❤️9953056974
 
young call girls in Vivek Vihar🔝 9953056974 🔝 Delhi escort Service
young call girls in Vivek Vihar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Vivek Vihar🔝 9953056974 🔝 Delhi escort Service
young call girls in Vivek Vihar🔝 9953056974 🔝 Delhi escort Service
 
Verified Trusted Call Girls Adugodi💘 9352852248 Good Looking standard Profil...
Verified Trusted Call Girls Adugodi💘 9352852248  Good Looking standard Profil...Verified Trusted Call Girls Adugodi💘 9352852248  Good Looking standard Profil...
Verified Trusted Call Girls Adugodi💘 9352852248 Good Looking standard Profil...
 
VIP Call Girls Service Mehdipatnam Hyderabad Call +91-8250192130
VIP Call Girls Service Mehdipatnam Hyderabad Call +91-8250192130VIP Call Girls Service Mehdipatnam Hyderabad Call +91-8250192130
VIP Call Girls Service Mehdipatnam Hyderabad Call +91-8250192130
 
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service 🧵
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service  🧵CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service  🧵
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service 🧵
 
VIP College Call Girls Gorakhpur Bhavna 8250192130 Independent Escort Service...
VIP College Call Girls Gorakhpur Bhavna 8250192130 Independent Escort Service...VIP College Call Girls Gorakhpur Bhavna 8250192130 Independent Escort Service...
VIP College Call Girls Gorakhpur Bhavna 8250192130 Independent Escort Service...
 
NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...
NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...
NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...
 
SCRIP Lua HTTP PROGRACMACION PLC WECON CA
SCRIP Lua HTTP PROGRACMACION PLC  WECON CASCRIP Lua HTTP PROGRACMACION PLC  WECON CA
SCRIP Lua HTTP PROGRACMACION PLC WECON CA
 
CALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun service
 
Call Girls in Kalkaji Delhi 8264348440 call girls ❤️
Call Girls in Kalkaji Delhi 8264348440 call girls ❤️Call Girls in Kalkaji Delhi 8264348440 call girls ❤️
Call Girls in Kalkaji Delhi 8264348440 call girls ❤️
 
WAEC Carpentry and Joinery Past Questions
WAEC Carpentry and Joinery Past QuestionsWAEC Carpentry and Joinery Past Questions
WAEC Carpentry and Joinery Past Questions
 
Fashion trends before and after covid.pptx
Fashion trends before and after covid.pptxFashion trends before and after covid.pptx
Fashion trends before and after covid.pptx
 
Kurla Call Girls Pooja Nehwal📞 9892124323 ✅ Vashi Call Service Available Nea...
Kurla Call Girls Pooja Nehwal📞 9892124323 ✅  Vashi Call Service Available Nea...Kurla Call Girls Pooja Nehwal📞 9892124323 ✅  Vashi Call Service Available Nea...
Kurla Call Girls Pooja Nehwal📞 9892124323 ✅ Vashi Call Service Available Nea...
 

Introduction to design_patterns

  • 2. 2 Contents • Overview • Definitions • Design Pattern Catalog • Design Patterns Descriptions • Benefits & Drawbacks
  • 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

Editor's Notes

  1. 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.
  2. Several definitions are given here to provide a more comprehensive treatment. Please take note of these keywords: recurring, standard, common, solution, problem, multiple, context.
  3. 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
  4. 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
  5. Frequency of use: Medium high (4 of 5) Sample Application: Creating different documents (e.g., Report, Resume, etc…) from a base Document class.
  6. 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.
  7. 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 &amp; Graphics from the Java API are façade classes for parsing font files and rendering text into pixels.
  8. 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