简体   繁体   English

如何通知事件的类组件?

[英]How do I notify a class component of an event?

I have class named A and its component class called B. 我有一个名为A的类,它的组件类叫做B.

public class A {
    B myB;

    ...
    public void bWasUpdated(){
       ...
        List<String> list = myB.connections;
    }
}

If I have an instance of B in my class A and if that instance of B gets updated somehow, how can I notify my instance of class A and call bWasUpdated() ? 如果我的A类中有B的实例,并且如果B的实例以某种方式更新,那么如何通知我的A类实例并调用bWasUpdated()

I tried interfaces but ended up really confused. 我试过接口但最终真的很困惑。 I guess I don't quite understand how to pass data yet between an object and its component. 我想我不太明白如何在对象及其组件之间传递数据。

EDIT 编辑

public class B {
    ArrayList<String> connections;

    ....

    public void listen(){

        ...
        if(foundNewConnection){
            this.connections.add(theNewConnection);
            //Notify class A about this new connection;
        }
    }
}

You should use a Listener , which is a form of the pattern called the Observer pattern . 您应该使用一个Listener ,它是一种称为Observer模式的模式

First, add this interface to your B class: 首先,将此接口添加到B类:

public interface ChangeListener {
    public void onChangeHappened();
}

Second, add a listener variable to B with a setter: 其次,使用setter将侦听器变量添加到B:

private ChangeListener listener;

public void setChangeListener(ChangeListener listener) {
    this.listener = listener;
}

Third, make A implement the ChangeListener interface and register itself as a listener: 第三,使A实现ChangeListener接口并将自己注册为监听器:

public class A implements ChangeListener {

public A() {
    myB = new B();
    myB.setChangeListener(this);
}

...

public void onChangeHappened() {
    // do something with B now that you know it has changed.
}

And last but not least, call your listener inside B when something changes: 最后但并非最不重要的是,当事情发生变化时,请在B内部召唤听众:

public void someMethodInB() {
    // change happened
    if (listener != null) {
        listener.onChangeHappened();
    }
}

如果B - A的内部类,则可以在B setter(或其他状态修饰符)中调用A.this.bWasUpdated();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM