Observer Design Pattern

Observer Design Pattern Definition: Defines a one-to-many dependency between objects so that when an object changes state, all its dependents will be notified and automatically updated. The java pseudo-code implementation is as follows:
import java.util.ArrayList;

public class SubjectImpl implements Subject{//Subject is an interface for binding observers, unbinding observers and notifications
	
	ArrayList<Observer> observers = new ArrayList<Observer>(); //Used to save the observer Observer is an interface that defines the method to be implemented by the observer
	// bind the observer
	@Override
	public void registerObserver(Observer o) {
		observers.add(o);
	}
	
	//unbind the observer
	@Override
	public void removeObserver(Observer o) {
		observers.remove(o);
	}
	//Notify observer
	@Override
	public void notifyObserver() {
		for(Observer o :observers){
			o.change();	
		}
	}

}


The Observer design pattern achieves decoupling between two objects. Both subjects and observers only need to be programmed according to their own interface specification.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326680252&siteId=291194637