Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use singleton everytime I have a class that should have only 1 instance? [duplicate]

Many times i have a class that should have only 1 instance. Is the best practice is to use singleton?


2 Answers

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.

like image 129
Eric Stein Avatar answered Sep 02 '25 19:09

Eric Stein


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.

like image 36
omer schleifer Avatar answered Sep 02 '25 17:09

omer schleifer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!