定义:定义了对象之间的一对多依赖,让多个观察者对象同时监听某一个主题对象,当主题对象发生变化时,它的依赖者(观察者)都会收到通知并更新
适用场景:
关联行为场景,建立一套触发机制
优点:
1.观察者和被观察者之间建立一个抽象的耦合
2.观察者模式支持广播通讯
缺点:
观察者之间有过多的细节依赖,提高时间消耗及程序复杂度
使用得当,要避免循环调用
import java.util.Observable; public class Course extends Observable { private String courseName; public Course(String courseName) { this.courseName = courseName; } public String getCourseName() { return courseName; } public void produceQuestion(Course course,Question question){ System.out.println(question.getUserName()+"在"+course.courseName+"提交了问题"); setChanged(); notifyObservers(question); } }
public class Question { private String userName; private String questionContent; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getQuestionContent() { return questionContent; } public void setQuestionContent(String questionContent) { this.questionContent = questionContent; } }
import java.util.Observable; import java.util.Observer; public class Teacher implements Observer { private String teacherName; public Teacher(String teacherName) { this.teacherName = teacherName; } @Override public void update(Observable o,Object arg){ Course course=(Course)o; Question question=(Question)arg; System.out.println(teacherName+"老师的"+course.getCourseName()+"课程接收到一个"+question.getUserName()+"提交的问答:"+question.getQuestionContent()); } }
public class Test { public static void main(String[] args) { Course course=new Course("Java设计模式精讲"); Teacher teacher=new Teacher("laoshi"); course.addObserver(teacher); Question question=new Question(); question.setUserName("Geelly"); question.setQuestionContent("Java"); course.produceQuestion(course,question); } }