使用侦听器时避免循环依赖

时间:2016-01-07 20:08:34

标签: java jface

在这个非常简单的例子中,避免循环依赖的最佳方法是什么?我想避免内联SelectionChangedListener,因为它是一个相当大/复杂的类。

class SomeGui extends Dialog {
    TreeViewer someWidget;
    SelectionChangedListener someListener;

    private void someMethod(){
        someListener = new SelectionChangedListener(this);
        someWidget.addSelectionChangedListener(someListener);
    }

    public void doSomething(){
    }
}

class SelectionChangedListener implements ISelectionChangedListener{
    SomeGui reference;

    public SelectionChangedListener(SomeGui reference) {
        this.reference = reference;
    }

    @Override
    public void selectionChanged(SelectionChangedEvent event) {
        reference.doSomething();
    }
}

1 个答案:

答案 0 :(得分:0)

通常你会让听众成为一个内心的人。对话框的类,然后它有一个隐含的对话框实例:

class SomeGui extends Dialog {
    TreeViewer someWidget;
    ISelectionChangedListener someListener;

    private void someMethod() {
        someListener = new SelectionChangedListener();
        someWidget.addSelectionChangedListener(someListener);
    }

    void doSomething() {
    }

    private class SelectionChangedListener implements ISelectionChangedListener {
        @Override
        public void selectionChanged(SelectionChangedEvent event) {
           doSomething();
        }
    }
}

注意:如果您使用的是Java 8,则可以简化为:

class SomeGui extends Dialog {
    TreeViewer someWidget;
    ISelectionChangedListener someListener;

    private void someMethod() {
        someListener = this::widgetSelectionChanged;
        someWidget.addSelectionChangedListener(someListener);
    }

    private void doSomething() {
    }

    private void widgetSelectionChanged(SelectionChangedEvent event) {
       doSomething();
    }

}