- Forward


The Singleton Pattern
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Some applications require exactly one instance of a class:
    • Windowing systems with one event queue
    • Word processors with one menu bar (for all documents)
  • Unfortunately, constructors can be called repeatedly:
    • In one method
    • In one class
    • Across multiple classes
Requirements of a Singleton
Back SMYC Forward
  • Create and return an instance of itself if one doesn't exist
  • Return the existing instance if one does exist
One Implementation of the Singleton Pattern
Back SMYC Forward

singleton

An Example
Back SMYC Forward
A FileViewer
javaexamples/singleton/v1/FileViewer.java (Fragment: skeleton)
 
An Example (cont.)
Back SMYC Forward
A FileViewer
javaexamples/singleton/v1/FileViewer.java (Fragment: createInstance)
 
An Example (cont.)
Back SMYC Forward
Using a FileViewer
javaexamples/singleton/v1/FileChooser.java (Fragment: valueChanged)
 
Thread Safety
Back SMYC Forward
  • A Potential Problem:
    • If the createInstance() method might be called by multiple threads, problems can arise
  • Resolutions:
    • Make createInstance() synchronized
    • Use eager initialization (i.e., instantiate instance when it is declared)
An Example (cont.)
Back SMYC Forward
Using Eager Instantiation
javaexamples/singleton/v2/FileViewer.java (Fragment: eagerInstantiation)
 


javaexamples/singleton/v2/FileViewer.java (Fragment: createInstance)
 
There's Always More to Learn
Back -