Tuesday, June 30, 2009

Observer and Observable Example

In Java we have Observer interface and Observable class, Below program gives a sample use of Observer and Observable

import java.util.Observable;

public class Employee extends Observable {
float salary;

public void setSalary(float newSalary) {
salary = newSalary; // salary has changed
setChanged(); // mark that this object has changed, MANDATORY
notifyObservers(new Float(salary)); // notify all observers, MANDATORY
}
}

import java.util.Observable;
import java.util.Observer;

public class Manager implements Observer {

public void update(Observable obj, Object arg) {
System.out.println("A change has happened and new salary is " + arg);
}
}


public class Demo {
public static void main(String[] args) {
Employee e = new Employee();
Manager m = new Manager();
e.addObserver(m); // register for observing
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (i == 5) {
e.setSalary(100);
}
}
}
}

No comments: