Consider the following: I have controllers and views in a client-application. As this runs purely on the client side, each controller must only exist once.
At first I thought about implementing everything as Singletons but this doesn’t really feel right for a few reasons.
A few is instantiated like so:
abstract class View(controller: Controller)
now in each view I do certain things, based on the controller I got.
Some controllers need to have parameters set upon initialization, this speaks for a class, rather than a singleton. (Of course I could do: MyObject.set(whatever) but that’s neither clean nor nice)
Now my idea was to create a simple mutable HashMap for the controllers and store the classes as keys and exactly one corresponding object as a value.
Now upon each initialization I just check the HashMap for an instance and if there is one already, I return that instead.
Seems hacky though.
Of course I could just stick with classes all the way, but I’m not sure if this is a good way. I mean, if I instantiate new Controllers every few seconds … (It’s a game we’re talking about, so there is already a lot of calculations going on)
2
At a high level, you’re essentially asking:
Is building a Controller cache better than using singletons?
I would argue that in your situation, yes, it is. And here’s why.
From your description it doesn’t sound like you need the semantics of a singleton here. Your game would be just fine if you instantiated a new Controller every time one was needed.
In other words, your requirement isn’t: All references to a Controller must resolve to a single unique Controller state.”
Instead, your requirement seems to be: When retrieving a Controller instance, it should be fast.
That is an argument for using a cache. Not singletons.
If you want to implement that cache using a HashMap then go for it 🙂
4