Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a singleton class use an interface?

I read at many places that singletons can use interfaces. Some how I am unable to comprehend this.

like image 718
AJ. Avatar asked Sep 30 '09 09:09

AJ.


People also ask

What is singleton interface?

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.

Can singleton class implement an interface C#?

Also, generally, if a singleton is not a static class, it can implement any interface you want.

What is the best way to implement a singleton class?

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.

What is singleton class in Java and how can we make a class 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.


2 Answers

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.

like image 192
nkr1pt Avatar answered Sep 22 '22 03:09

nkr1pt


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;
  }
}
like image 24
Nick Holt Avatar answered Sep 18 '22 03:09

Nick Holt