您真正想要做的是设置事件驱动模型,以在事件发生时触发侦听器(在您的情况下,说变量值已更改)。这不仅对于Java,而且对于其他编程语言也非常普遍,尤其是在UI编程的情况下(尽管不一定如此)
通常,这可以通过执行以下步骤来完成:
- 确定在事件触发时侦听器应实现的接口。对于您的情况,可以将其称为VariableChangeListener并将接口定义为:
public interface VariableChangeListener { public void onVariableChanged(Object... variableThatHasChanged);}
您可以提出任何您认为对侦听器重要的论点。通过抽象到接口中,您可以灵活地在变量已更改的情况下执行必要的操作,而不必将其与发生事件的类紧密耦合。
- 在事件发生的类中(同样,对于您的情况,变量可能会更改的类),添加一种方法来注册事件的侦听器。如果调用接口VariableChangeListener,则将有一个方法,例如
// while I only provide an example with one listener in this method, in many cases // you could have a List of Listeners which get triggered in order as the event // occurres public void setVariableChangeListener(VariableChangeListener variableChangeListener) {this.variableChangeListener = variableChangeListener; }默认情况下,没有人在听事件
- 如果发生事件(变量已更改),则将触发监听器,代码看起来像
if( variablevalue != previousValue && this.variableChangeListener != null) {// call the listener here, note that we don't want to a strong coupling// between the listener and where the event is occurring. With this pattern// the pre has the flexibility of assigning the listenerthis.variableChangeListener.onVariableChanged(variablevalue); }同样,这是在编程中对事件或变量更改做出基本反应的非常普遍的做法。在Javascript中,您可以看到它是onclick()的一部分,在Android中,您可以检查事件驱动器模型,以了解各种侦听器,例如在Button
onclick事件上设置的OnClickListener。在您的情况下,您将仅基于不同事件触发侦听器,即在变量更改时



