Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between using singleton class and class with static methods?

Tags:

java

what is need of singleton(state is fixed ) class if I have class with static methods (fixed behaviors )?

like image 401
Neel Salpe Avatar asked Jan 17 '26 09:01

Neel Salpe


2 Answers

With the singleton it is easier to replace the instance if needed, for example, for testing.

like image 57
fortran Avatar answered Jan 19 '26 23:01

fortran


I think one of the best arguments for using a singleton rather than a class with purely static methods is that it makes it easier to introduce multiple instances if this turns out to be required later. It is not uncommon to see applications where there is no fundamental reason to restrict a class to a single instance, but the authors did not envision any extension of their code, and found it easier to use static methods. Then when you want to extend the application later it is much harder to do so.

Being able to replace the instance for testing (or other reasons) is also a good point, and being able to implement an interface also helps with this.

like image 37
Ben Avatar answered Jan 19 '26 22:01

Ben



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!