场景
观察者模式(Observer Pattern)
定义了对象之间的一对多依赖,让多个观察者对象同时监听一个主体对象,当主体对象发生变化
时,它的所有依赖者(观察者)都会收到通知并更新,属于行为型模式。
观察者模式有时也叫发布订阅模式。
观察者模式在现实生活中的应用:朋友圈动态通知、线上会议软件提问问题、邮件通知、广播通知等。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
观察者模式示例-线上会议提问问题
线上会议教学,当学生提问时,如果设置了指定的老师回答,对应老师就会收到消息或邮件通知。
创建Meeting类
package com.ruoyi.demo.designPattern.observerPattern; import java.util.Observable; public class Meeting extends Observable { private String name ="线上会议"; private static Meeting meeting = null; private Meeting(){} public static Meeting getInstance(){ if(null == meeting){ meeting = new Meeting(); } return meeting; } public String getName(){ return name; } public void publishQuesting(Question question){ System.out.println(question.getUserName()+"在"+this.name+"上提了一个问题。"); setChanged(); notifyObservers(question); } }
创建问题类
package com.ruoyi.demo.designPattern.observerPattern; public class Question { private String userName; private String content; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
创建老师类
package com.ruoyi.demo.designPattern.observerPattern; import java.util.Observable; import java.util.Observer; /** * 观察者 */ public class Teacher implements Observer { private String name; public Teacher(String name){ this.name = name; } public void update(Observable o,Object arg){ Meeting meeting = (Meeting) o; Question question = (Question) arg; System.out.println("=========================="); System.out.println(name+"老师,您好\n"+"您收到了一个来自"+question.getUserName()+"的问题,问题内容:\n"+question.getContent()+"\n"+"提问者:"+question.getUserName()); } }
客户端测试代码
package com.ruoyi.demo.designPattern.observerPattern; public class observerTest { public static void main(String[] args) { Meeting meeting = Meeting.getInstance(); Teacher zhangsan = new Teacher("张三"); Teacher lisi = new Teacher("李四"); meeting.addObserver(zhangsan); meeting.addObserver(lisi); Question question = new Question(); question.setUserName("霸道"); question.setContent("观察者模式的优缺点是啥?"); meeting.publishQuesting(question); } }
运行结果