Singleton Design Pattern

The Singleton Design Pattern is a type of creational pattern that ensures a class has only one instance while providing a public access point to that instance.

This pattern is useful for preventing the repeated instantiation of resource-heavy objects …


This content originally appeared on DEV Community and was authored by Tommy

The Singleton Design Pattern is a type of creational pattern that ensures a class has only one instance while providing a public access point to that instance.

This pattern is useful for preventing the repeated instantiation of resource-heavy objects and for objects needed to coordinate actions across the application system.

It is commonly used for things like database connection pools, logging, cache management, configuration classes, etc.

public class Singleton {

    // Create a private static instance of the class
    private static Singleton instance;

    // Make the constructor private so it cannot be instantiated outside
    private Singleton() {
    }

    // Provide a public static method to get the instance
    public static Singleton getInstance() {
        // Instantiate the singleton instance if null
        if (instance == null) {
            instance = new Singleton();
        }

        // return the singleton instance
        return instance;
    }
}


This content originally appeared on DEV Community and was authored by Tommy


Print Share Comment Cite Upload Translate Updates
APA

Tommy | Sciencx (2024-09-22T04:28:45+00:00) Singleton Design Pattern. Retrieved from https://www.scien.cx/2024/09/22/singleton-design-pattern-3/

MLA
" » Singleton Design Pattern." Tommy | Sciencx - Sunday September 22, 2024, https://www.scien.cx/2024/09/22/singleton-design-pattern-3/
HARVARD
Tommy | Sciencx Sunday September 22, 2024 » Singleton Design Pattern., viewed ,<https://www.scien.cx/2024/09/22/singleton-design-pattern-3/>
VANCOUVER
Tommy | Sciencx - » Singleton Design Pattern. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/09/22/singleton-design-pattern-3/
CHICAGO
" » Singleton Design Pattern." Tommy | Sciencx - Accessed . https://www.scien.cx/2024/09/22/singleton-design-pattern-3/
IEEE
" » Singleton Design Pattern." Tommy | Sciencx [Online]. Available: https://www.scien.cx/2024/09/22/singleton-design-pattern-3/. [Accessed: ]
rf:citation
» Singleton Design Pattern | Tommy | Sciencx | https://www.scien.cx/2024/09/22/singleton-design-pattern-3/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.