Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

Java Observer pattern

// Java Observer pattern (Simple version)
public interface Subject {
	public void registerObserver(Observer o);
	public void removeObserver(Observer o);
	public void notifyObservers();
}

public interface Observer {
	public void update(int value);
}

public class SimpleSubject implements Subject {
	private List<Observer> observers;
	private int value = 0;
	
	public SimpleSubject() {observers = new ArrayList<Observer>();}
	
	public void registerObserver(Observer o) {observers.add(o);}
	
	public void removeObserver(Observer o) {observers.remove(o);}
	
	public void notifyObservers() {
		for (Observer observer : observers) {
			observer.update(value);
		}
	}
	
	public void setValue(int value) {
		this.value = value;
		notifyObservers();
	}
}

public class SimpleObserver implements Observer {
	private int value;
	private Subject simpleSubject;  // who to subscribe
	
	public SimpleObserver(Subject simpleSubject) {
		this.simpleSubject = simpleSubject;
		simpleSubject.registerObserver(this);
	}
	
	public void update(int value) {
		this.value = value;
		display();
	}
	
	public void display() {System.out.println("Value: " + value);}
}

public class Example {
	public static void main(String[] args) {
		SimpleSubject simpleSubject = new SimpleSubject();
		SimpleObserver simpleObserver = new SimpleObserver(simpleSubject);
		simpleSubject.setValue(80);		// output: 80
		simpleSubject.removeObserver(simpleObserver);
	}
}
Source by fr.wikipedia.org #
 
PREVIOUS NEXT
Tagged: #Java #Observer #pattern
ADD COMMENT
Topic
Name
6+3 =