Java references objects that are not in scope
When my java project gets bigger, a question will always pop up: is there a simple way to reference specific objects that super or GetParent () cannot reference The following figure should illustrate my current problem:
For each filelistitem, I want to implement a new filelistitemcontroller, which requires methods from protocolcontroller Is there any way to reference the protocolcontroller object instantiated by main in filelistitems instead of passing it through MainWindow, filelistcontentpanel and filelistitems?
First of all, thank you for all your answers
I am using my project model, view, control mode
The single mode sounds interesting, but my feeling is that it doesn't solve my problem Here are some codes to illustrate my problem:
public class Main { public static void main(String [ ] args) { ProtocolController pc = new ProtocolController(); mainWindow mw = new mainWindow(); } } public class ProtocolController { File protocol; public ProtocolController(File protocol){ this.protocol = protocol; } public void writeSomethingToProtocolFile(String something){ // write something to th protcol file specified by the object } } public class mainWindow { public mainWindow(){ FileListContentPanel flcp = new FileListContentPanel(); } } public class FileListContentPanel { public FileListContentPanel(){ int numListItems = 10; for (int i = 0; i < 10; i++) { FileListItem fli = new FileListItem(); FileListItemController flic = new FileListItemController(fli); } } } public class FileListItemController { public FileListItemController(FileListItem fli){ } public void addSomethingToProtocol(String something){ // at this point I want to use a method from the ProtocolController class instantiated by the main method } }
Solution
There are different ways
For example, if you only need one protocolcontroller instance, you can use singleton pattern Then, each filelistitemcontroller can retrieve the same protocolcontroller object
class ProtocolController { private static instance; private ProtocolController() { } public static ProtocolController getInstance() { if (instance == null) { instance = new ProtocolController(); } return instance; } }
You can then get the protocolcontroller from the filelistitemcontroller GetInstance (), and then invoke the required method.