package Obverser;//抽象观察者public interface Obverser {public void update();}//具体观察者class student implements Obverser {public void update() {System.out.println("学生观察者,跑进教室");}}class teacher implements Obverser {public void update() {System.out.println("老师观察者走进教室");}}
package Obverser;import java.util.ArrayList;//抽象被观察者public interface subject {public void notifysubject();public void attach(Obverser ob);public void detach(Obverser ob);}//具体被观察者class concreteSubject implements subject {private ArrayList obverserlist new ArrayList();public void notifysubject() {ArrayList en observers();int i obverserlist.size();for (int j 0; j < i; j) {((Obverser) obverserlist.get(j)).update();}}private ArrayList observers() {return obverserlist;}public void attach(Obverser ob) {obverserlist.add(ob);}public void detach(Obverser ob) {obverserlist.remove(ob);}}
package Obverser;public class client {public static void main(String[] args) {Obverser s1 new student();Obverser s2 new student();Obverser s3 new student();Obverser t1 new teacher();concreteSubject c new concreteSubject();c.attach(s1);c.attach(s2);c.attach(s3);c.attach(t1);c.notifysubject();}}
运行结果