I need to share 1 instance between several classes.
The Connect class has methods to create a URL and to download data, and the ui is the interface (swing form) through which I get the data to build the url (dates theat comprise the url).
What’s the best way to do it?
Thought of:
1) Making it global by:
public class Global {
public static Connect c;
}
2) Making the instance in main(), and passing it through objects.
public static void main(String[] args) throws IOException {
Connect c = new Connect(); // get url to download from
ui form = new ui(c); // the form to get data from
.
.
.
What seems more reasonable, if any?
Thank you.
The preferred way is usually to pass the instance into the constructor of whatever class needs it. That way, it’s not a guess whether or not someone has set up
Global.cand when it should be available to use. It also clearly documents that each class requires aConnectobject. Another benefit is that if your code ever changes and you want your UI class to no longer rely on the same GlobalConnectinstance, you no longer have to change all your code that pulls a magic instance from this global context, and you can just pass in a different object.Do a search for something along the lines of “why are global variables bad” or “why are singleton accessors bad” and you’ll get a lot more detail than my explanation. There are uses for them, but if you can avoid them up front you may save some headache down the line. As with everything, there are trade-offs for each.