The Observer Pattern is used when there is a one-to-many relationship between objects. For example, when an object is modified, dependent objects are automatically notified. The observer model belongs to the behavioral model.
import java.util.ArrayList; import java.util.List; class ObserverPattern { public static void main(String[] args) { Debit zhangSan = new ZhangSan(); zhangSan.borrow(new WangWu()); zhangSan.borrow(new ZhaoSi()); // State change zhangsan.notifyCredits (); // State change zhangsan.notifyCredits (); } } interface Debit { void borrow(Credit credit); void notifyCredits(); } class ZhangSan implements Debit { private List<Credit> allCredits = new ArrayList<>(); private Integer state = 0; @override public void borrow(Credit) {allCredits. Add (Credit); } @Override public void notifyCredits() { for (Credit credit : allCredits) { credit.takeMoney(); } } } interface Credit { void takeMoney(); } class WangWu implements Credit { @Override public void takeMoney() { System.out.println("WangWu take money"); } } class ZhaoSi implements Credit { @Override public void takeMoney() { System.out.println("ZhaoSi take money"); }}Copy the code