In my program I have a menu system in which I have a separate class for each menu, for example MainMenu would be a separate class. But the class is only supposed to be instanced once, and after I instance it, it is saved in a list which is all is used for after that. Should I use another solution than a separate class? Or should I make the constructor private and then make a private instance inside the class? I feel like this violates OOP, but I don't see another solution.
Asked
Active
Viewed 67 times
0
-
[Here's a relevant post](http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java). – resueman Jan 20 '16 at 21:20
1 Answers
4
Don't make the constructor private, this makes problems when you later want to unit test it.
Just instantiate it once. There are no software terrorist which secretly instantiate your class multiple times. And avoid Singeltons, you nearly cannot reset the instance later when trying to unit test that.

AlexWien
- 28,470
- 6
- 53
- 83
-
1I work with software terrorists every day. We call them "coworkers". Making a class a singleton will deter misuse much more effectively than "Do not instantiate directly!!" comments. – Andreas Jan 20 '16 at 21:31
-
-
Likely, a better solution is for InzaneNova to look into an injection framework. Spring perhaps. – Andreas Jan 20 '16 at 21:32
-
If you use singeltons, then you are the head of the Software terrorist. It is nearly impossible to instantate them in unit tests. And my restSingleton() solution using Reflection is not fine. If you create an APi like ios, things might change. – AlexWien Jan 20 '16 at 21:33
-
1No need to bring a DI framework in for this; Java has a great built in DI system - it's using `new` and passing parameters to constructors! – tddmonkey Jan 20 '16 at 21:33
-
-
-
It's a myth that singletons are hard to test. Of course you don't want to over-use them, but singletons do serve a purpose. Whether the constructor is `private` is irrelevant for testability. Uncle Bob covers the topic in [The little singleton](http://blog.8thlight.com/uncle-bob/2015/06/30/the-little-singleton.html). – Mick Mnemonic Jan 20 '16 at 21:56