Skip to content

Week 7 - Singleton Design Pattern

The Singleton Design Pattern

Classification

  • Creational Design Pattern

Pattern Definition

  • Ensure a class only has one instance, and provide a global point of access to it.

Common to all Singleton Implementations

  • Private constructor to restrict instantiation of the class from other classes.
  • Private static variable of the same class that is the only instance of the class.
  • Public static method that returns the instance of the class, this is the global access point for the outer world to get the instance of the singleton class.

Representations

Mermaid Graph

Lazy Initialization Singleton
1
2
3
4
5
6
classDiagram
    class Singleton {
        -Singleton uniqueInstance$
        -Singleton()
        +getInstance()$: Singleton
    }

Bill Pugh Singleton

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
classDiagram
    Singleton --> SingletonHelper : Contains
    class Singleton {
        -class SingletonHelper$
        -Singleton()
        +getInstance()$: Singleton
    }
    class SingletonHelper {
        -Singleton INSTANCE$
    }

UML

Singleton
Bill Pugh Singleton

Usage

  • The singleton pattern is used anywhere you need One-and-Only-One copy of an object. Interacting with files, databases, logging, caching, and or system drivers are all areas where singleton objects are necessary to control access to a single object.

Real World Usages

  • Database and File System Connections
  • Serializing logging.
  • Singular access to device drivers
  • Singular access to cache store/retrieval
  • Thread Pools

Application to my Real World Application

  • I have a DAOStage class that implements Stage and contains a Singleton for various database connections. The Singleton class is called Database and its getInstance method returns a concrete Database connection from its Nested class that uses a Factory Method to decide the database type to connect to, and sets the Singleton object to it at runtime.

Java Code Example

Main Take-Aways from the textbook

  • Examine your performance and resource constraints and carefully choose an appropriate Singleton implementation for multithreaded applications (and we should consider all applications multithreaded!).
  • Beware of the double- checked locking implementation; it isn’t thread safe in versions before Java 5.
  • Be careful if you are using multiple class loaders; this could defeat the Singleton implementation and result in multiple instances.
  • You can use Java’s enums to simplify your Singleton implementation.

Main OO Principles of Singleton Pattern

  • None this week! The Singleton stands alone!