public class MySingleton{
private static final MySingleton INSTANCE = new MySingleton();
private MySingleton(){}
public static getInstance(){
return INSTANCE;
}
}
Is this the right way to implement a Singleton. If yes then what is the necessity of the final keyword ?
Singleton classes, if properly implemented, do not need to be declared final in order to not be extended. Since all the constructors of the singleton class are private, you can't extend that class. In fact, singleton classes are effectively final.
In Java, Singleton is a design pattern that ensures that a class can only have one object. To create a singleton class, a class must implement the following properties: Create a private constructor of the class to restrict object creation outside of the class.
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching and thread pool.
In Java, the final keyword can be used while declaring an entity. Using the final keyword means that the value can't be modified in the future. This entity can be - but is not limited to - a variable, a class or a method.
Final will ensure the instance is not changeable after creation. If you're only including a constructor, and no setters, it's not a big deal. No one can change your INSTANCE and you are not changing it.
Not a bad idea to leave it there in case the class is later changed. Immutability offers some advantages (easier serialization, insurance against someone changing your object behind your back, etc).
It is harder to put immutability back in than it is to take it out. Write your code defensively so no one can mess it up later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With