From the course: Advanced Java: Hands-on with Streams, Lambda Expressions, Collections, Generics and More
Unlock this course with a free trial
Join today to access over 25,300 courses taught by industry experts.
Implementing the Singleton pattern - Java Tutorial
From the course: Advanced Java: Hands-on with Streams, Lambda Expressions, Collections, Generics and More
Implementing the Singleton pattern
- Now that we've discussed use cases and benefits of the singleton design pattern, let's see how to implement it. There are several strategies for implementing the singleton pattern and we'll go over two common approaches, eager initialization and lazy initialization. Eager initialization creates the instance of the singleton class when the class is loaded. This approach is simple and works well when the single instance is not resource intensive or when it's guaranteed to be used during the application's lifetime. And I'm very eager to show you how to do just that. So, here's a eager singleton. As you can see, the class is final, meaning that it's not allowed to have child classes and the constructor is also private, meaning it's not allowed to have child classes. This is an eager singleton because we give a static instance of itself that will recreate at that spot. So, we made the class final to make sure that it…