Why use singleton instead of static class?

前端 未结 7 721
迷失自我
迷失自我 2020-12-08 04:02

When would a singleton actually be easier or better than a static class? It seems to me creating a singleton is just extra effort that\'s not actually needed, but I\'m sure

7条回答
  •  無奈伤痛
    2020-12-08 04:39

    Singletons always seemed a bit redundant to me. I prefer static classes, and if I need different behavior, I combine it with a dependency injection and a provider.. I don't know what pattern this is, or if it has a name, but it usually goes something like this:

    public interface IFooProvider {
      Bar FooBar();
    }
    
    public static class Foo {
      public static readonly IFooProvider FooProvider { get; set; }
      public Bar FooBar() { return FooProvider.FooBar(); }
    }
    

    Then I just make sure to set the provider somewhere in my init method. It's easy enough to add lazy initialization if you want to by setting the default provider at class initialization. Best of all, it allows you to change the behavior while still getting the aesthetic of using static classes.

提交回复
热议问题