如何为变量创建更改侦听器

如何为变量创建更改侦听器

本文介绍了如何为变量创建更改侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我使用语句int someVariable; 定义了一些变量.当代码运行时,变量的值会发生变化.

Let's say I have some variable defined using the statementint someVariable;. While the code runs, the variable's value changes.

我如何跟踪这个变量的变化?我如何实现一些行为类似于 onSomeVariableChangedListener 的监听器?

How can I track the changes in this variable? How could I implement some Listener that behaves like onSomeVariableChangedListener?

我还需要知道一个页面中的其他方法何时被执行,以便我可以在另一个类中设置一个监听器.

I also need to know when some other method in one page has been executed so I can set a Listener in another class.

推荐答案

这是将变量隐藏在 setter/getter 对后面的众多原因之一.然后,在 setter 中,您可以通知您的侦听器此变量已以适当的方式修改.正如其他人所评论的那样,没有内置的方法可以完全按照您的意愿行事,您需要自己实施.

This is one of the many reasons to hide variables behind setter/getter pairs. Then, in the setter you can notify your listener that this variable has been modified in the appropriate way. As the others have commented, there is no built in way to do exactly what you want, you need to implement it yourself.

或者 Benjamin 提出了一个有趣的模式,称为装饰器模式,如果相关代码无法修改,它可能对您有用.您可以在维基百科中查找更多信息

Alternatively Benjamin brings up an interesting pattern, called the Decorator pattern, which might be useful to you if the code in question cannot be modified. You can look up more info at Wikipedia

这个想法是围绕一个对象构建一个兼容的包装器.假设您有问题的对象属于 MyClass 类型.

The idea is to build a compatible wrapper around an object. Lets say your object in question is of type MyClass.

class MyClass{
    public void doFunc(){...}
}

class MyLoggedClass extends MyClass{
    MyClass myObject;

    public void doFunc(){
        //Log doFunc Call
        myObject.doFunc();
    }
}

代替

MyClass object = new MyClass();

你会使用

MyClass object = new MyLoggedClass(new MyClass());

现在您的其余代码将照常使用对象,除了每个函数调用都将被记录或通知等

Now your rest of the code would use object as per normal, except that each function call will be logged, or notified, etc.

正如您在维基百科中所见,这通常是通过相关类继承的接口来完成的,但这在您的情况下可能是不可能的.

As you will see in Wikipedia, this is typically done via an interface that the class in question inherits from, but this may not be possible in your case.

这篇关于如何为变量创建更改侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:15