#
Observer
This tutorial explains to you the design pattern named Observer (which is a Structural Pattern).
#
Observer Pattern - theory
Observer
Design Pattern in Java is used when we want to have a one-to-many dependency and when one object change a state
("salary" value in Employee class, in my example) all its dependents are notified and updated automatically.
The Observer pattern is also known as Publish-Subscribe
or Dependents.
Take a look at the following UML diagram representing the Observer design pattern (for my example):
#
Observer Pattern - example
Here is an example of using the Observer Design Pattern in Java:
package observer.java.pattern.example;
import java.util.ArrayList;
import java.util.List;
public class Employee {
int id;
String name;
int salary;
private List<Observer> observers = new ArrayList<Observer>();
public Employee(int id, String name, int salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public int getSalary() {
return salary;
}
public void setName(String name) {
this.name = name;
}
public void setSalary(int salary) {
this.salary = salary;
notifyAllObservers();
}
public void notifyAllObservers(){
for (Observer observer : observers) {
observer.sendMessage();
}
}
public void addObserver(Observer observer){
observers.add(observer);
}
}
package observer.java.pattern.example;
public interface Observer {
public abstract void sendMessage();
}
package observer.java.pattern.example;
public class HumanResourcesObs implements Observer {
private Employee emp;
public HumanResourcesObs(Employee employee){
this.emp = employee;
this.emp.addObserver(this);
}
@Override
public void sendMessage() {
System.out.println( "Human Resources are informed about the new salary ("+ emp.getSalary()+ ") of Mr. "+emp.getName() );
}
}
package observer.java.pattern.example;
public class HighManagementObs implements Observer {
private Employee emp;
public HighManagementObs (Employee employee){
this.emp = employee;
this.emp.addObserver(this);
}
@Override
public void sendMessage() {
System.out.println( "High Management is informed about the new salary ("+ emp.getSalary()+ ") of Mr. "+emp.getName() );
}
}
package observer.java.pattern.example;
public class ObserverJavaPatternExample {
public static void main(String[] args) {
Employee emp = new Employee(10, "John Brown", 2000);
new HumanResourcesObs(emp);
new HighManagementObs(emp);
emp.setSalary(2200);
System.out.println("-------------------------------------------------");
emp.setSalary(3300);
}
}
When you run this example you will receive the following result: