I read at many places that singletons can use interfaces. Some how I am unable to comprehend this.
Defining a singleton object type is a special case of defining an object type. The difference is that a singleton object type does not require a provider. Alternatively, we might say that its unique instance is its own provider.
Also, generally, if a singleton is not a static class, it can implement any interface you want.
Eager initialization: In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a Singleton class. By making the constructor as private you are not allowing other class to create a new instance of the class you want to create the Singleton.
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.
Every class can implement an interface, and a Singleton is just a "normal" class that makes sure that only one instance of it exists at any point in time apart from the other business logic it may implement. This also means that a Singleton has at least 2 responsibities and this is not good OO design as classes should only have 1 responsibility and make sure they are good at that responsibility, but that is another discussion.
Something like:
public interface MyInterface
{
}
And
public class MySingleton implements MyInterface
{
private static MyInterface instance = new MySingleton();
private MySingleton()
{
}
public static MyInterface getInstance()
{
return instance;
}
}
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