JavaRush /Java Blog /Random EN /Why is Singleton needed?
KarmaHacker
Level 30
Новосибирск

Why is Singleton needed?

Published in the Random EN group
I'm currently solving a big problem at level 27. There we are asked to create a StatisticManager class and make it a singleton. OK no problem! Later, in other classes of the program I have to call StatistcManager's methods, and here I start to encounter small annoying moments, I have to write a reference variable StatisticManager statisticManager = StatisticManager.getInstance(); statisticManager.method(); or like this: StatisticManager.getInstance().method(); That's a lot of extra letters! It would be much easier to make the class static and write it like this: StatisticManager.method(); I think perhaps a singleton has something to gain over a static class? I read an article on Habré and only strengthen my doubts. Singleton, at least in this task, is redundant. So far, I see only one use for a singleton - if we need to save resources and create an object not immediately, but sometime later, when we need it. In other cases, a static class is just fine. On Habré they also write something about inheritance, but I can barely imagine such a situation, and probably not very often either. If I'm wrong, correct me please. I just want to better understand the design principles and maybe this will help someone else figure it out :)
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION