Quando usar Singleton (Design Pattern)
2011-03-23 20:09:44
2011-03-23 18:44:25
Autor: Sony Santos
https://gigawiki.com/sony/quando-usar-singleton-design-pattern
Permalink: https://gigawiki.com/973
categ = guidelines; idioma = inglês
Meu resumo pessoal é:
Use só se a inicialização do objeto depende de coisas que não existem no momento da definição.

Mas isso foi inspirado no seguinte trecho, que não fala especificamente isso (fonte):

Singletons do indeed have their uses. I would summarize their usefulness as:

"A Singleton should be used to represent on object of which, according to the fundamental design or requirements, there can be at most one instance; and there is data or resources associated with the object which incurs a measurable cost." Here's what I mean.

1) You shouldn't use a Singleton in the case where there are many of something, but we only happen to be interested in one. If there could conceivably be two in the system, instantiate one explicitly.

2) Many uses of a Singleton can be replaced by a class with all static methods and data. If you can do this without performance penalty, do it.

3) You should consider a Singleton if there is a noticeable cost to setting up the object: for example if it's a physical resource which needs to be initialized, or it relies on some lookup table that needs to be initialised. If that is the case, with a Singleton you can defer the initialisation cost until the first use of the object, whereas a static class will usually initialise on app start. If the object is never used you never pay the initialisation cost.
blog comments powered by Disqus