开发者

how to find change value of any field of a class?

开发者 https://www.devze.com 2023-02-08 03:06 出处:网络
Let\'s say I have 2 classes A.java and B.java and there is private int a in A class like that : public class A {

Let's say I have 2 classes A.java and B.java and there is private int a in A class like that :

public class A {
    private int a;
}

and I use this class in class B that I want to know or attach an handler to the field int a开发者_运维问答; that to know it's value change in every asynchronous call. Let me more explain :

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
     }
}

Which design pattern should I use? What solution do you offer?

Thanks in advance,

hilal


Observer pattern or here

B registers itself as the observer of A. A is the subject and B is the observer

how to find change value of any field of a class?

.

Whenever the "a" changes, A notify()'s all the registered Observer's.


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

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

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

Add a B object in A, and recall B's method.


You could turn class A into a JavaBean and add support for PropertyListeners. However, you first have to register one with your A() instance.

0

精彩评论

暂无评论...
验证码 换一张
取 消