user584018
user584018

Reputation: 11304

what is the benefit to create a singleton class by implementing a interface?

if I have a interface like below,

 public interface IMethods
  {
    void M1();
    void M2();
  }

then I want to create a singleton class by inheriting above interface, then what's the benefit in context of re use of singleton class and how?

Upvotes: 0

Views: 81

Answers (2)

Haney
Haney

Reputation: 34742

I'm not entirely sure what you're asking, but if you're asking "what's the benefit of implementing this interface as a singleton" the answer is the same benefit that singleton always offers: "a guarantee of one instance no matter how many places it's used". Singleton exists to enforce a single instance of a class with instance access vs static class and methods/properties. An example implementation:

public class Methods : IMethods
{
    // Singleton instance
    private static readonly IMethods _instance = new Methods();

    // Private constructor to enforce singleton
    private Methods()
    {

    }

    // The instance getter
    public static IMethods Instance
    {
        get
        {
            return _instance;
        }
    }

    public void M1()
    {

    }

    public void M2()
    {

    }
}

The thing that will hose you here is the fact that the Instance property is not exposed on the IMethods interface, so getting it requires the instance type to be Methods and not IMethods which sort of defeats the purpose of the inheriting the interface.

Often, people use dependency injection frameworks to set the lifetime of an interface's implementation to singleton AKA shared instance instead. It is more "OO friendly".

Upvotes: 3

Adam Houldsworth
Adam Houldsworth

Reputation: 64467

The singleton aspect is just one implementation of the IMethods contract, giving you the benefit of the singleton pattern, assuming that is what you need.

The benefit of exposing that singleton through an interface is that the consumer doesn't need to care how it is implemented, just that it is implemented and they can use it. At a later date if you suddenly need a regular instance as opposed to a singleton, you can change that without impacting consumers.

This happens very frequently with DI containers, where you can usually configure the lifecycle of a binding to be in singleton scope.

If you use the singleton directly and never really use the interface, then there is little use in the interface. If the singleton is being used without really needing to constrain it to a single instance, then there is little use in adopting the singleton pattern.

Upvotes: 3

Related Questions