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,
hilalObserver pattern or here
B registers itself as the observer of A. A is the subject and B is the observer
.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.
精彩评论