如何找到班级任何领域的变化值?

时间:2011-01-31 06:27:53

标签: java oop design-patterns event-handling

假设我有2个课程A.javaB.java,并且A类中有private int a

public class A {
    private int a;
}

我在B类中使用这个我想知道的类,或者将一个处理程序附加到字段int a; 知道它在每次异步调用中的值变化。让我来解释一下:

public class B {
     private A aClass;

     public static void main (String ... args) {
           aClass = new A(); // now the int a; is changed how do I know this

           // user may call many asynchronous method in class A and I want to know
           // the changing value of int a; from A class in B class
     }
}

我应该使用哪种设计模式?你提供什么解决方案?

提前致谢,
新月

3 个答案:

答案 0 :(得分:1)

Observer patternhere

B将自身注册为A的观察者.A是主语,B是观察者in this diagram

每当" a"更改,A通知()所有已注册的观察者。

答案 1 :(得分:1)

public class A {
    private int a;
    private B observer;

    void setA(int i) {
        a = i;
        observer.notify();
    }

    void registerObserver(B b) {
        observer = b;
    }
}

在A中添加B对象,并调用B的方法。

答案 2 :(得分:0)

您可以将A类转换为JavaBean并添加对PropertyListeners的支持。 但是,您首先必须在A()实例中注册一个。