当前位置 : 主页 > 网络编程 > 其它编程 >

GOF行为型模式:观察者模式

来源:互联网 收集:自由互联 发布时间:2023-07-02
packageObverser;抽象观察者publicinterfaceObverser{publicvoidupdate();}具体观察者classstudentimple package Obverser;//抽象观察者public interface Obverser {public void update();}//具体观察者class student implements Obverser
packageObverser;抽象观察者publicinterfaceObverser{publicvoidupdate();}具体观察者classstudentimple

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();}}

运行结果 在这里插入图片描述

上一篇:HTTP笔记(二)
下一篇:没有了
网友评论