SlideShare une entreprise Scribd logo
1  sur  31
Télécharger pour lire hors ligne
Design Patterns in JAVA
Design Patterns in JAVA
Brian Zitzow, @bzitzow
Web Developer, Student, Father
Michael Kirby
Sasiwipa Nakdee
Twitter: @lilwipa
● Girlfriend
● Puts up with me
● Feeds me after class
● Thank You Sasi!
Design Patterns
Huh?
Design Patterns
In software engineering, a design pattern is a general
reusable solution to a commonly occurring problem within a
given context in software design.
A design pattern is not a finished design that can be
transformed directly into source or machine code. It is a
description or template for how to solve a problem that can
be used in many different situations.
Patterns are formalized best practices that the
programmer must implement themselves in the application.
Before Inserting Data ...
H2 db = null;
dbUrl = “db://database/location”;
dbUser = “username”;
dbPass = “password”;
// Initialize Database Object
db = new H2(dbUrl, dbUser, dbPass);
db.openConnection();
// Insert Data, Query Data, Do Stuff
db.closeConnection();
Every time we want to use the database
● Get database credentials
● Instantiate a new database object
● Open and close database connection
Looping
DirectoryScanner dirScan = new DirectoryScanner();
List<File> files = dirScan.getList(dir);
for (int i = 0; i < files.size(); i++) {
// Instantiate Database
// Open Connection
// Close Connection
}
Looping Overhead
● Every iteration requires:
– Access to database credentials
– New object with every iteration
– Open & Close the resource
Looping Overhead Example
SuperD (File Duplication Checker)
● 52,000+ Database Connections
● 8GB of RAM used
● System Locked
● Application Crashed
Looping Overhead – Solved!
DirectoryScanner dirScan = new DirectoryScanner();
List<File> files = dirScan.getList(dir);
// Instantiate Database
// Open Connection
for (int i = 0; i < files.size(); i++) {
// Insert & Query Stuff
}
// Close Connection
What about multiple files?
Public Class UserFiles
{
// Database Credentials
// Instantiate Database
// Open Connection
// Close Connection
}
Public class DupeChecker
{
// Database Credentials
// Instantiate Database
// Open Connection
// Close Connection
}
What about multiple files?
● Duplicate Code (load credentials every time)
● Multiple instances of same object
– Instantiate an open resource multiple times is
resource intensive
● Could inject into objects
– Creates object dependencies AKA coupling
– Adds to object complexity
● Contributors (are drunk, stressed, naïve,
resentful or otherwise unaware and)
instantiate Database objects within the loops.
Solution?
The Singleton Pattern
The Singleton Pattern
Ensures a class has only one instance, and
provides a global point of access to it.
All further references to objects of the singleton
class refer to the same underlying instance.
The Singleton Pattern
Without Pattern:
H2 db = null;
dbUrl = “db://database/location”;
dbUser = “username”;
dbPass = “password”;
// Initialize Database Object
db = new H2(dbUrl, dbUser, dbPass);
db.openConnection();
// Insert Data, Query Data, Do Stuff
db.closeConnection();
With Pattern:
Database.getInstance().execute(sql);
Database.getInstance().closeConnection();
How does it work?
● Private Constructor
● Static Method
● Static Property
Private Constructor
Public Class Database
{
private Database() {}
}
Private Constructor
● Object cannot be instantiated outside itself
● Weird, right?
● Can never, ever have more than one instance
● What about the first instance?
Static Method
Public Class Database
{
Public static H2 getInstance() {
}
}
Static Method
● Public - can be accessed anywhere
● Static - can be accessed w/out instantiation
● Checks if instance of object exists
– If true : return instance
– If false: instantiate, assign, and return
Static Property
Public Class Database
{
private static H2 uniqueInstance;
}
Static Property
● Private - can only be set within the class
● Static - static methods cannot access
instance variables. They can, however, access
class variables aka static properties.
The Singleton
Public Class Database
{
private static H2 uniqueInstance;
public static H2 getInstance() {
if (uniqueInstance == null) {
this.uniqueInstance = new Database();
this.uniqueInstance.openConncetion();
}
return this.uniqueInstance;
}
private Database() {}
}
The Singleton
Database.getInstance().execute(sql);
Database.getInstance().closeConnection();
The Singleton
● Only one instance can ever be created
● Global access point, static method()
● Contributors can safely use in or out of loop
Gotchas:
● Multi-Threading, tweak it slightly :)
THANK YOU
Thank YouThank You

Contenu connexe

Tendances

Alex Zvolinskiy ” From Manual Testing To Automation”
Alex Zvolinskiy ” From Manual Testing To Automation”Alex Zvolinskiy ” From Manual Testing To Automation”
Alex Zvolinskiy ” From Manual Testing To Automation”Dakiry
 
Acceptance Test Driven Development and Robot Framework
Acceptance Test Driven Development and Robot FrameworkAcceptance Test Driven Development and Robot Framework
Acceptance Test Driven Development and Robot FrameworkSteve Zhang
 
Commit Hooks: the Subtle Hammer
Commit Hooks: the Subtle HammerCommit Hooks: the Subtle Hammer
Commit Hooks: the Subtle HammerBen McGraw
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascriptGarrison Locke
 
Acceptance Test Drive Development with Robot Framework
Acceptance Test Drive Development with Robot FrameworkAcceptance Test Drive Development with Robot Framework
Acceptance Test Drive Development with Robot FrameworkRamdhan Hidayat
 
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Steven Smith
 
HibernateClass room training
HibernateClass room  trainingHibernateClass room  training
HibernateClass room trainingJayarajus
 
Tech Talk Tokyo #2 tetsuya matsuzawa
Tech Talk Tokyo #2 tetsuya matsuzawaTech Talk Tokyo #2 tetsuya matsuzawa
Tech Talk Tokyo #2 tetsuya matsuzawaRarejob
 
FEI 2013 - Nette framework
FEI 2013 - Nette frameworkFEI 2013 - Nette framework
FEI 2013 - Nette frameworkAdam Štipák
 
1. Java Hello world
1. Java Hello world1. Java Hello world
1. Java Hello worldPlay Store
 

Tendances (15)

Alex Zvolinskiy ” From Manual Testing To Automation”
Alex Zvolinskiy ” From Manual Testing To Automation”Alex Zvolinskiy ” From Manual Testing To Automation”
Alex Zvolinskiy ” From Manual Testing To Automation”
 
Acceptance Test Driven Development and Robot Framework
Acceptance Test Driven Development and Robot FrameworkAcceptance Test Driven Development and Robot Framework
Acceptance Test Driven Development and Robot Framework
 
Commit Hooks: the Subtle Hammer
Commit Hooks: the Subtle HammerCommit Hooks: the Subtle Hammer
Commit Hooks: the Subtle Hammer
 
Why do I hate Hibernate?
Why do I hate Hibernate?Why do I hate Hibernate?
Why do I hate Hibernate?
 
Thinking Functionally
Thinking FunctionallyThinking Functionally
Thinking Functionally
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
Why Do I Hate Hibernate?
Why Do I Hate Hibernate?Why Do I Hate Hibernate?
Why Do I Hate Hibernate?
 
Ps02 cint24 mvc in php
Ps02 cint24 mvc in phpPs02 cint24 mvc in php
Ps02 cint24 mvc in php
 
Js tips & tricks
Js tips & tricksJs tips & tricks
Js tips & tricks
 
Acceptance Test Drive Development with Robot Framework
Acceptance Test Drive Development with Robot FrameworkAcceptance Test Drive Development with Robot Framework
Acceptance Test Drive Development with Robot Framework
 
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013
 
HibernateClass room training
HibernateClass room  trainingHibernateClass room  training
HibernateClass room training
 
Tech Talk Tokyo #2 tetsuya matsuzawa
Tech Talk Tokyo #2 tetsuya matsuzawaTech Talk Tokyo #2 tetsuya matsuzawa
Tech Talk Tokyo #2 tetsuya matsuzawa
 
FEI 2013 - Nette framework
FEI 2013 - Nette frameworkFEI 2013 - Nette framework
FEI 2013 - Nette framework
 
1. Java Hello world
1. Java Hello world1. Java Hello world
1. Java Hello world
 

Similaire à Design Patterns in Java: The Singleton Pattern

Dependency Injection in Spring in 10min
Dependency Injection in Spring in 10minDependency Injection in Spring in 10min
Dependency Injection in Spring in 10minCorneil du Plessis
 
Dapper: the microORM that will change your life
Dapper: the microORM that will change your lifeDapper: the microORM that will change your life
Dapper: the microORM that will change your lifeDavide Mauri
 
Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Greg Szczotka
 
Data Abstraction for Large Web Applications
Data Abstraction for Large Web ApplicationsData Abstraction for Large Web Applications
Data Abstraction for Large Web Applicationsbrandonsavage
 
OOP, API Design and MVP
OOP, API Design and MVPOOP, API Design and MVP
OOP, API Design and MVPHarshith Keni
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code FirstJames Johnson
 
Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14Diego Freniche Brito
 
Decoupling Drupal mit dem Lupus Nuxt.js Drupal Stack
Decoupling Drupal mit dem Lupus Nuxt.js Drupal StackDecoupling Drupal mit dem Lupus Nuxt.js Drupal Stack
Decoupling Drupal mit dem Lupus Nuxt.js Drupal Stacknuppla
 
Agile Data: Building Hadoop Analytics Applications
Agile Data: Building Hadoop Analytics ApplicationsAgile Data: Building Hadoop Analytics Applications
Agile Data: Building Hadoop Analytics ApplicationsDataWorks Summit
 
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
 
Agile Data Science: Building Hadoop Analytics Applications
Agile Data Science: Building Hadoop Analytics ApplicationsAgile Data Science: Building Hadoop Analytics Applications
Agile Data Science: Building Hadoop Analytics ApplicationsRussell Jurney
 
Agile Data Science by Russell Jurney_ The Hive_Janruary 29 2014
Agile Data Science by Russell Jurney_ The Hive_Janruary 29 2014Agile Data Science by Russell Jurney_ The Hive_Janruary 29 2014
Agile Data Science by Russell Jurney_ The Hive_Janruary 29 2014The Hive
 
Agile Data Science: Hadoop Analytics Applications
Agile Data Science: Hadoop Analytics ApplicationsAgile Data Science: Hadoop Analytics Applications
Agile Data Science: Hadoop Analytics ApplicationsRussell Jurney
 
Managing a Project the Drupal Way - Drupal Open Days Ireland
Managing a Project the Drupal Way - Drupal Open Days IrelandManaging a Project the Drupal Way - Drupal Open Days Ireland
Managing a Project the Drupal Way - Drupal Open Days IrelandEmma Jane Hogbin Westby
 

Similaire à Design Patterns in Java: The Singleton Pattern (20)

Dependency Injection in Spring in 10min
Dependency Injection in Spring in 10minDependency Injection in Spring in 10min
Dependency Injection in Spring in 10min
 
Dapper: the microORM that will change your life
Dapper: the microORM that will change your lifeDapper: the microORM that will change your life
Dapper: the microORM that will change your life
 
Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014
 
Data Abstraction for Large Web Applications
Data Abstraction for Large Web ApplicationsData Abstraction for Large Web Applications
Data Abstraction for Large Web Applications
 
OOP, API Design and MVP
OOP, API Design and MVPOOP, API Design and MVP
OOP, API Design and MVP
 
La sql
La sqlLa sql
La sql
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
Solid OOPS
Solid OOPSSolid OOPS
Solid OOPS
 
Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14
 
Intro to Drush
Intro to DrushIntro to Drush
Intro to Drush
 
Decoupling Drupal mit dem Lupus Nuxt.js Drupal Stack
Decoupling Drupal mit dem Lupus Nuxt.js Drupal StackDecoupling Drupal mit dem Lupus Nuxt.js Drupal Stack
Decoupling Drupal mit dem Lupus Nuxt.js Drupal Stack
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
D7 as D8
D7 as D8D7 as D8
D7 as D8
 
Agile Data: Building Hadoop Analytics Applications
Agile Data: Building Hadoop Analytics ApplicationsAgile Data: Building Hadoop Analytics Applications
Agile Data: Building Hadoop Analytics Applications
 
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
 
Agile Data Science: Building Hadoop Analytics Applications
Agile Data Science: Building Hadoop Analytics ApplicationsAgile Data Science: Building Hadoop Analytics Applications
Agile Data Science: Building Hadoop Analytics Applications
 
Agile Data Science by Russell Jurney_ The Hive_Janruary 29 2014
Agile Data Science by Russell Jurney_ The Hive_Janruary 29 2014Agile Data Science by Russell Jurney_ The Hive_Janruary 29 2014
Agile Data Science by Russell Jurney_ The Hive_Janruary 29 2014
 
Agile Data Science: Hadoop Analytics Applications
Agile Data Science: Hadoop Analytics ApplicationsAgile Data Science: Hadoop Analytics Applications
Agile Data Science: Hadoop Analytics Applications
 
Managing a Project the Drupal Way - Drupal Open Days Ireland
Managing a Project the Drupal Way - Drupal Open Days IrelandManaging a Project the Drupal Way - Drupal Open Days Ireland
Managing a Project the Drupal Way - Drupal Open Days Ireland
 

Design Patterns in Java: The Singleton Pattern

  • 1.
  • 3. Design Patterns in JAVA Brian Zitzow, @bzitzow Web Developer, Student, Father Michael Kirby
  • 4. Sasiwipa Nakdee Twitter: @lilwipa ● Girlfriend ● Puts up with me ● Feeds me after class ● Thank You Sasi!
  • 6. Design Patterns In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations. Patterns are formalized best practices that the programmer must implement themselves in the application.
  • 7. Before Inserting Data ... H2 db = null; dbUrl = “db://database/location”; dbUser = “username”; dbPass = “password”; // Initialize Database Object db = new H2(dbUrl, dbUser, dbPass); db.openConnection(); // Insert Data, Query Data, Do Stuff db.closeConnection();
  • 8. Every time we want to use the database ● Get database credentials ● Instantiate a new database object ● Open and close database connection
  • 9. Looping DirectoryScanner dirScan = new DirectoryScanner(); List<File> files = dirScan.getList(dir); for (int i = 0; i < files.size(); i++) { // Instantiate Database // Open Connection // Close Connection }
  • 10. Looping Overhead ● Every iteration requires: – Access to database credentials – New object with every iteration – Open & Close the resource
  • 11. Looping Overhead Example SuperD (File Duplication Checker) ● 52,000+ Database Connections ● 8GB of RAM used ● System Locked ● Application Crashed
  • 12. Looping Overhead – Solved! DirectoryScanner dirScan = new DirectoryScanner(); List<File> files = dirScan.getList(dir); // Instantiate Database // Open Connection for (int i = 0; i < files.size(); i++) { // Insert & Query Stuff } // Close Connection
  • 13. What about multiple files? Public Class UserFiles { // Database Credentials // Instantiate Database // Open Connection // Close Connection } Public class DupeChecker { // Database Credentials // Instantiate Database // Open Connection // Close Connection }
  • 14. What about multiple files? ● Duplicate Code (load credentials every time) ● Multiple instances of same object – Instantiate an open resource multiple times is resource intensive ● Could inject into objects – Creates object dependencies AKA coupling – Adds to object complexity ● Contributors (are drunk, stressed, naïve, resentful or otherwise unaware and) instantiate Database objects within the loops.
  • 16.
  • 17.
  • 19. The Singleton Pattern Ensures a class has only one instance, and provides a global point of access to it. All further references to objects of the singleton class refer to the same underlying instance.
  • 20. The Singleton Pattern Without Pattern: H2 db = null; dbUrl = “db://database/location”; dbUser = “username”; dbPass = “password”; // Initialize Database Object db = new H2(dbUrl, dbUser, dbPass); db.openConnection(); // Insert Data, Query Data, Do Stuff db.closeConnection(); With Pattern: Database.getInstance().execute(sql); Database.getInstance().closeConnection();
  • 21. How does it work? ● Private Constructor ● Static Method ● Static Property
  • 22. Private Constructor Public Class Database { private Database() {} }
  • 23. Private Constructor ● Object cannot be instantiated outside itself ● Weird, right? ● Can never, ever have more than one instance ● What about the first instance?
  • 24. Static Method Public Class Database { Public static H2 getInstance() { } }
  • 25. Static Method ● Public - can be accessed anywhere ● Static - can be accessed w/out instantiation ● Checks if instance of object exists – If true : return instance – If false: instantiate, assign, and return
  • 26. Static Property Public Class Database { private static H2 uniqueInstance; }
  • 27. Static Property ● Private - can only be set within the class ● Static - static methods cannot access instance variables. They can, however, access class variables aka static properties.
  • 28. The Singleton Public Class Database { private static H2 uniqueInstance; public static H2 getInstance() { if (uniqueInstance == null) { this.uniqueInstance = new Database(); this.uniqueInstance.openConncetion(); } return this.uniqueInstance; } private Database() {} }
  • 30. The Singleton ● Only one instance can ever be created ● Global access point, static method() ● Contributors can safely use in or out of loop Gotchas: ● Multi-Threading, tweak it slightly :)