Java refers to objects that are not in scope

one question that always comes up when my java project gets bigger is if there is an easy way to link to a specific object that cannot be referenced by super or getParent (). The following graph should illustrate my current problem: enter image description here

For each FileListItem, I want to install a new FileListItemController, which needs methods from ProtocolController. Is there a way to refer to the ProtocolController object set mainly in FileListItems, other than passing it through mainWindow, FileListContentPanel, FileListItems?


Thanks first to all your answers.

I use a model, view, control template for my project.

, , . , :

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
    }
}
+4
3

.

, ProtocolController, singleton pattern. FileListItemController ProtocolController.

class ProtocolController {

    private static instance;

    private ProtocolController() { }

    public static ProtocolController getInstance() {
        if (instance == null) {
            instance = new ProtocolController();
        }
        return instance;
    }
}

ProtocolController.getInstance() FileListItemController .

0

FileListItemController, Singleton "Lazy instantiation".

ProtocolController FileListItemController :

FileListItemController fileListItemControllerInstance = FileListItemController.getInstance();

FileListItem FileListItemController, Factory ( Factory )

ProtocolController FileListItemController factory. ProtocolController Factory, .

FileListItem Factory FileListItemController.

0

Model-View-Controller.

FileListItem ( ). Controller, View (FileListControlPanel) Model. , , "" , .

https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

0
source

Source: https://habr.com/ru/post/1667378/


All Articles