十七 Java设计模式解析(观察者模式)

2018-10-13  本文已影响0人  十丈_红尘
1️⃣概念

定义:定义了对象之间的一对多的依赖,让多个观察者对象同时监听某一个主题对象,当主题对象发生变化时,它的所有依赖者(观察者)都会收到通知并更新;
类型:行为型;


2️⃣适用场景

关联行为场景,建立一套触发机制;


3️⃣优点

观察者与被观察者之间建立了一个抽象的耦合;
观察者模式支持广播通信;


4️⃣缺点

观察者之间有过多的细节依赖,提高时间消耗以及程序的复杂度;
使用要得当,要避免循环调用;


5️⃣观察者模式Coding

1 创建Course类

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

    }
}

2 创建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;
    }
}

3 创建Teacher类

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

4 编写测试类

public class Test {
    public static void main(String[] args) {
        Course course = new Course("设计模式");
        Teacher teacher1 = new Teacher("Alpha");
        Teacher teacher2 = new Teacher("Beta");

        course.addObserver(teacher1);
        course.addObserver(teacher2);

        //业务逻辑代码
        Question question = new Question();
        question.setUserName("mufeng");
        question.setQuestionContent("Java的主函数如何编写");

        course.produceQuestion(course,question);
    }
}
5 UML类图

6️⃣观察者模式源码解析
JDK : EventListener监听器 image.png

Guava

public class GuavaEvent {
    @Subscribe
    public void subscribe(String str){
        //业务逻辑
        System.out.println("执行subscribe方法,传入的参数是:" + str);
    }
}
public class GuavaEventTest {
    public static void main(String[] args) {
        EventBus eventbus = new EventBus();
        GuavaEvent guavaEvent = new GuavaEvent();
        eventbus.register(guavaEvent);
        eventbus.post("post的内容");
    }
}
在使用Guava来实现观察者模式的时候,可以直接使用@Subscribe这个注解,将这个注解放在方法上边就直接实现了观察者;
上一篇下一篇

猜你喜欢

热点阅读