Should the singleton be designed so that it can be created and destroyed at any time in program or should it be created so that it is available in life-time of program. Which one is best practice? What are the advantages and disadvantages of both?
EDIT :- As per the link shared by Mat, the singleton should be static. But then what are the disadvantages of making it destroyable? One advantage is it memory can be saved when it is not useful.
|
|
|||||||||||
|
|
Whatever floats your boat. If you need to destroy it (maybe to reclaim memory or maybe it has state that's no longer valid) you should do that. If it holds state that's inconvenient to recreate on demand, you should keep it around. If you have no particular reason to destroy it I think you should keep it around. |
|||
|
|
|
Singleton's introduce the same dependency as a global variable. Singleton's tend to introduce difficult to test implementations. That said, I favor a singleton design that is implemented as a standard object. The singleton-ness of the object is an implementation detail where only one instance is created and made available. The singleton instance is most often useful when it is lazily-constructed. That is only construct the object when it is needed. The lazy instantiation of the object can often be used to help with testability of objects that are dependent on the singleton. For testing purposes you might introduce a mock object or alternative implementation that is instantiated. Singleton's have there place in your toolbox. Understanding their limitations is important to using them successfully. |
|||
|
|
|
Singletons are completely appropriate solutions to some design problems. However, how the singleton is implemented matters here. As a C# example,
Would be an example of a singleton that should never be destroyed. Its possible to have an internal static field to store the singleton reference, and to do a lazy instantiation if the internal value is null. But you then have to worry about ensuring singlethreaded access to test for null, potentially create and then obtain the singleton instance, just so you could free up the memory from this one object at some point. It is really bad practice to create singletons by declaring the class static. It makes object destruction impossible, as well as making it a nightmare for mocking the interface in your unit tests. |
|||
|
|
|
A singleton should never be available, it's the definition of anti-pattern. That said, the supposed benefit of the design is that it handles creation order and lifetime in such a way as to guarantee the thing always exists. Making it destroyable rather defeats the purpose. |
|||||||||||||||
|
|
The best practice is just to not use a Singleton in the first place. But if you're going to use one, making it destroyable is even worse, and it's quite remarkable to have something worse than a regular Singleton. |
|||||
|