Pergunta

i do not want to know the difference between singleton and static class first of all. i like to know when people should use singleton class and when static class.

in my apps i use static class for helper or utility method and use singleton for db connection and error logger class. but with the help of static class can be used to return sql db connection object and as well as error logging system.

i really like to know about other senior developer where they use singleton class and where they use static class.

it will very helpful if some one discuss this matter with sample situation and sample code. thanks

Foi útil?

Solução 2

A very broad question but will give you the first reason that popped into my head for use of a Singleton.

A Singleton is more appropriate than a dedicated static class when you need to manage the lifetime of some cached objects. Singletons are perfect when you want to refresh state without having to worry about thread safety, for example if you have a class that is being used as a singleton and it has many cached properties or lists that incoming requests may want access to.

The Refresh() method can simply be setting the current instance to a new instance and not having to refresh individual properties of the class:

private static YourClass instance = new YourClass();  // first instance

public static void Refresh(){
    instance = new YourClass();  // creates a new, refreshed instance while not needing to worry about thread safety
}

public static YourClass Instance{
      get{
         return instance;
      }
}

Outras dicas

If you are creating loosely coupled system, then there is no way you can use static classes (because they cannot implement abstraction and cannot be injected). Static classes also very hard to mock, so it's not your choice if you are doing TDD or simple unit-testing. So, I use them only for dependencies which are not related to business requirements and should not be mocked. E.g. infrastructure logic like logging or mapping.

I also use static classes for extension methods if I cannot extend existing class, but want handy member-like API. Usually this is a also infrastructure-related extensions, like mapping, or serialization, which do not contain business logic.

I usually use singleton classes when I am creating a database access object. Where I can have the instance of the object anywhere inside an application.

I usually stay away from static classes, which the exception of an occasional loader class when loading particular assets.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top