Singleton Pattern


The Singleton pattern is a creational design pattern that lets you ensure that a class has only one instance across the entire application, while providing a global access point to this instance.

To implement this pattern, we store an instance of the class in itself, and return it 

Example

In an application we have a Database class, and we only want one instance of the database across the entire application, to make sure the data in it is consistent. We make it a Singleton:

public class Database {
    private static Database instance;

    private static Database () { }

    public static Database getInstance() {
        if (instance == null) instance = new Database();
        return instance;
    }
}

  1. Private static instance of the class
  2. Private constructor, so that no instances of this class can be made externally
  3. Public static method to get the unique instance

Design principles (link):

  • (NOK) This pattern violates the Single Responsibility Principle, because the class then has two responsibilities: the initial purpose, and the managing of its instance.

Relations with Other Patterns





Comments

Popular Posts