Properties:
- When object state changes, lets interested parties know about the changes.
- As the name implies observers, observe the object in question for state changes.
- Observers need to register to the object for receiving notifications when state change occurs.
Implementation:
- Observer interface declares methods to get updates .
- Observable interface declares methods to register, de-register for state changes.
- Concrete Observable class implements the Observable interface and responsible for notifying oberservers about stage changes.
Java Standard Library Implementations:
- java.util.EventListener
- javax.util.Observable
Example Usage:
public class ObserverDemo implements ActionListener {
private JButton b1, b2;
public ObserverDemo() {
JPanel panel = new JPanel();
b1 = new JButton("Button1");//Observable object
b2 = new JButton("Button2");//Observable object
//Register for state changes
b1.addActionListener(this);
b2.addActionListener(this);
panel.add(b1);
panel.add(b2);
}
// observer method
public void actionPerformed(ActionEvent e) {
if (b1.equals(e.getSource())) {
b2.setEnabled(true);
b1.setEnabled(false);
} else {
b1.setEnabled(true);
b2.setEnabled(false);
}
}
}
Comments
Post a Comment