2

I want create interface for singleton. But interface not can ban public constructor and describ static method. how to solve this of problems?

SkyN
  • 1,417
  • 4
  • 17
  • 32

3 Answers3

5

You cannot have a ISingleton interface for two reasons:

  1. Interfaces cannot have static members
  2. Interfaces cannot contain constructors

You could have a ASingleton abstract class if you liked.

Matt Mitchell
  • 40,943
  • 35
  • 118
  • 185
4

You can't, basically. Interfaces can't contain static methods, and can't put any constraints on what kind of constructors are available.

You might be interested in my notion of static interfaces, which would allow the idea of enforcing a particular static member to be present - but it wouldn't allow you to enforce the absence of a constructor.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

As others have said, you can't use an interface for that. What you can do is create a generic singleton class:

public static class Singleton<T> where T : new()
{
    public static T Instance { get; private set; }

    static Singleton() { Instance = new T(); }
}

This way you just use one generic class for all your singletons. Of course, you won't be able to initialize the singleton in different ways for different types (which can be changed implementing an interface on the instance or deriving classes).

Jaroslav Jandek
  • 9,463
  • 1
  • 28
  • 30