I have some Classes like Clipboard or ProcessRegister that I only want to run once in my Project, so only one instance.
My Question in now: How do I distribute those instances best in my Project.
ATM both are singleton and object they use the get an instance over the getInstance().
Another Idea of mine is to create a class Project, that has some static methods like getProjectClipboard()or getProcessRegister()that return the instances.
What is the best way to distribute them? Are there any patterns for that?
Greetings Dennis
There are mainly two patterns that can be used: the service locator, and dependency injection. The service locator pattern is probably the one you are referring to, where everywhere you look for a reference for these objects you explicitly retrieve it from a central location, which for simple java applications is usually a bunch of static methods. this is OK, and I don’t think there is an overall better approach here, just make sure that you have only one static method for each singleton, and that you call it always.
Then a few years ago, a shift of mentality became mainstream, dependency injection, and its more popular framework… Spring, with this paradigm, in each place you need to access this singletons, you don’t specify where they are, but your object get the correct references injected…
I would recommend you to look into dependency injection… and probably Spring, as it is the mainstream solution for it… I think that giving you more insgight into Spring is out of the scope of the question, but there is A LOT of documentation in Internet if you search for Spring tutorials or something similar…
Basically what you would do is create as spring beans each of your singletons, and then have spring injecting them into your objects… The caveat to this approach is that all of your objects have to be built by Spring, but in practice it doesn’t suppose any disadvantage, it will actually make your life easier in terms of testings, maintenance…