i) extend class Observable in Sender class.
ii) implement the Observer interface in Receiver class
The Sender class will be like this:
class Sender extends Observable{
private void doSomeTask(){
//Notify here
this.setChanged();
this.notifyObservers(object);
}
}
The class Receiver will look like this:
class Receiver implements Observer{
//Create observable object
Sender sender;
public Receiver(){
//add the observer object
this.sender.addObserver(this);
}
@Override
public void update(Observable observable, Object object){
//check the observable class
if(observable==this.sender){
//do some job here
}
}
}
The overriden method update of receiver class gets the notification from the observer. The update method takes the Observable object and the object sent from the Obvervable.
Advantages:
i) We can completely separate Model from Controller.
ii) Replaces creation of event handler which is lengthy process and requires more steps.
Disadvantages:
The one disadvantage is the observable class should be subclass of Observable and since inheritance in java does not allow multiple inheritance. So, if observable class needs to have more than one super class, it is not feasible, we need to change the implementation.