From the course: Spring: Design Patterns

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

The Singleton pattern

The Singleton pattern

From the course: Spring: Design Patterns

Start my 1-month free trial

The Singleton pattern

- The singleton pattern is the one pattern that I use almost as much as the factory pattern and with Spring I'm using that a lot more than I usually had because everything in Spring is a singleton. Well almost everything. So in Spring itself, every bean by default is a singleton. Unless you tell the application context otherwise, you're going to get a singleton. Now one thing to note is that this is not a classic singleton which is what we're going to discuss, but it behaves the exact same during the run time of your application. Beans, therefore, because they are singletons must be designed in a way that is thread safe. And that applies to all singleton classes in general. So this pattern is relatively straightforward. You have a class that stores a reference to itself. More specifically, to an instance of itself. You have a private constructor. Then you have a static getInstance method that returns a reference of self or if self is nul, it constructs it using the private constructor…

Contents