7

I would like to implement some kind of manager class in my application. It will be in charge of loading textures, processing them, distributing them etc...

At first, I wanted to make a global variable that simply contains an instance of my manager class. I found this question: https://stackoverflow.com/questions/4646577/global-variables-in-java. However, the users there seem to recommend to never use global variables.

Fine then, I once heard about Singletons, so I though I could use that instead. I mean, creating just one instance of my manager class sounds good. However, I found this other question: When is Singleton appropriate?, which basically tells me that Singletons are, in most scenarios, some kind of anti-pattern.

Now I am a bit lost - what other approach can I take to create my manager class, whose only requirement is to be accessible from anywhere?

Saturn
  • 3,937

3 Answers3

13

I suggest you look into using a dependency injection framework to achieve inversion of control.

Your "Manager" would not be a traditional Singleton, but you would only create one through the framework configuration. The "Manager" would also not be global, but every component that would need to use it would have it assigned.

smp7d
  • 4,221
4

whose only requirement is to be accessible from anywhere?

Did you actually read those two questions?

Having anything accessible from anywhere is design pitfall #1. It tightly couples your manager to your code, preventing that from being as flexible as it needs to be, making the code hard to test, hard to debug, hard to make concurrent...

No. If you must have a manager (I don't personally believe strongly in the link, but it's worth noting) then the app should make one and pass it into whatever needs a factory/manager for your textures/etc.

Telastyn
  • 110,259
4

it will be in charge of loading textures, processing them, distributing them

Well, I don't know your application, but this hardly sounds like a thing you need everywhere in your application, especially when your application is layered. You will need it somewhere in your application, and that is where you should pass it, no less, no more.

Moreover, these three responsibilities may be better split up into three classes - one for loading the textures, one for processing them and one for distributing them. The last one is probably the only one some other parts of your application may need to access from outside.

I would also consider to create an interface for your "texture manager", let's call it ITextureManager. The classes/objects needing access to the manager should get passed an ITextureManager instance through their constructor. Later on, you may consider the use of a DI framework, like @smp7d suggested, but actually that does not make a real difference concerning your question - if you are not able to decouple your code from a manager class "manually", you won't be more successfull when trying to use DI framework.

Doc Brown
  • 218,378