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.

Solution: Create a singleton

Solution: Create a singleton

- [Instructor] Alright, let's see how to solve this exercise. So we had to implement Singleton. We don't need to change anything in the answer class, so I'm going to scroll down a bit 'cause we had to modify the database connection. So what I've done I've given it an instance of its own type on line 15. And then in the constructor, I'm checking if this instance has been set already. If I somehow end up in the constructor and the instance is not null, I'm throwing an illegal state exception, this should not be possible. Also in the constructor I'm setting my database URL. And then probably the heaviest lifting was to get instance method, 'cause here we have to do some checks and there's multiple ways to get the correct answer because this implementation doesn't require that it also works in a multi-thread environments, but this one should work. So what I'm doing here, I'm first checking if the instance is null, and…

Contents