Many times i have a class that should have only 1 instance. Is the best practice is to use singleton?
Singletons are global state. They should be used only when it's really necessary, for the same reason that your code shouldn't have a ton of global variables.
"Should have" is the operative question. If the system doesn't care how many instances there are, don't make it a singleton. Only if the system truly requires that there be only one instance should you be thinking singleton.
Another pattern you can use is a factory method. The advantage here is that the factory may decide to return the same instance every time or a new instance. This will impose less limitations if you someday choose you don't want just a single instance, but let's say for example - a single instance per thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With