0

I have read this SO article, which tells us singletons are very very evil and should be avoided like an epidemic. It also tells us that singleton is just like a "global".

This makes me wonder if I really need something that acts like a program runtime state, would singleton be a bad idea?

For example I have a JavaFX application which can spawn many windows. Each of the windows have at least two stylesheets - one for controlling layout (like alignment etc), and another for theming.

The theme stylesheet can be switched out into another theme stylesheet at runtime, and it should globally affect all windows that are open at that instance. To me, it makes sense for me to make a singleton class that has a ObservableList of stylesheets, which all windows can bind their Scene's stylesheet property to.

Is this really a bad idea? If it affects testing, how exactly does it affect testing negatively? I understand each of the windows should be tested indepedently of each other, but the actual behavior is that all of them are supposed to look thematically the same. Furthermore, I don't think it should affect other areas which each window should really be independent of each other.

If this is really bad, what should be the approach to achieve the same result in the above example?

Community
  • 1
  • 1
Jai
  • 7,616
  • 2
  • 17
  • 43

1 Answers1

4

Actually you could get the same behavior using dependency injection.

In the main line of your application you'll instantiate a class like UIContext, and whenever you open a new window, you'll give that UIContext instance to its constructor.

All windows share the same UIContext instance, but it's not a singleton, it's just you've injected the whole UIContext into many other dependent classes.

That is, if you would need to implement tests, you could give a sample/fake UIContext to your windows with no hassle.

Matías Fidemraizer
  • 59,064
  • 16
  • 107
  • 181