There are two things in the Observer pattern: the Observer and the Subject. When the target changes, the observer dances with it and changes accordingly. This is the observer mode.

How is this done? Basically, there is a list of observers in the target. When the target changes, the list can be notified one by one, so that the observers make their own responses.

public class Client { public static void main(String a[]) { MySubject subject=new Cat(); MyObserver obs1,obs2,obs3; obs1=new Mouse(); obs2=new Mouse(); obs3=new Dog(); subject.attach(obs1); subject.attach(obs2); subject.attach(obs3); MyObserver obs4; obs4=new Pig(); subject.attach(obs4); subject.cry(); }}Copy the code