Steps to write callback routine.
Step1.
Write one interface with the method/methods need(s) to be invoked.
eg.
public interface ICallback {
public void notifyChange();
}
Step2.
Now write your binder class that will notify the object which is binded with it.
public class CallbackBinder {
private ICallback iCallback;
public void bindCallback (ICallback callBack){
this.iCallback = callBack;
}
//so whenever the property changes notify the class object.
public void notifyCallBack(){
iCallback.notifyChange();
}
}
Step3.
We need to bind the class with the callbackBinder to receive the notification. To do so we have to implement the ICallback interface and also pass the class reference to the binder.
public class TestClass implements ICallback {
public TestClass () {
new CallbackBinder ().bindCallback (this);
}
//you have to define the notify method and do the work as you want.
public void notifyChange () {
}
}
The notityChange method will be fired when the callbackBinder execute the notifyCallBack method.
We can also handle multiple classes objects with the same property. Suppose a single property has to bind with multiple classes objects and on changing the value of that property we need to call all the class objects. To accomplish this we can maintain a map which will contain the property as the key and the list of ICallback objects as value. We can make the CallbackBinder class as singleton to bind all the class objects to the same instance of the binder class.
private Map<String, List<ICallback>> propertyCallbackMap = new HashMap<String, List<ICallback>>();
when the property value is changed just get the object list and call notifyChange on them.
No comments:
Post a Comment