A text viewer mode and read case studies

First, the basic introduction

The observer pattern is an object behavioral pattern. It defines the dependencies between the subject an-many, when the state of an object is changed, all dependent on it are notified and updated automatically. In observer mode, the subject is the publisher's notice, notice when it does not need to know who its observers, there can be any number of observers to subscribe and receive notifications. The observer pattern is not only widely used in the interaction between software interface elements, in terms of interaction between business objects, rights management, also have a wide range of applications.

- quoted from Baidu Encyclopedia

Second, the definition of the pattern and characteristics

Defined observers (Observer) mode: refers to the presence of many dependencies among a plurality of objects, when a state of the object changes, all objects that depend on it have been notified and updated automatically. This mode is sometimes referred to publish - subscribe model, model - view mode, it is the object behavioral patterns.

  1. Reducing the coupling between the object and the observer, abstract coupling between the two.
  2. We have set up a trigger mechanism between the target and the observer.

Its main disadvantages are as follows:

  • Dependencies between the target and the observer is not completely removed, but there may be a circular reference.
  • When an object many observers, the conference notification spend a lot of time, it affects the efficiency of the program.

Third, the structure and mode of realization

Should pay attention to when implementing the observer pattern can not be called directly between the specific target audience and specific observer objects will keep the tight coupling between them, in violation of the principles of object-oriented design.
The main role of the observer mode are as follows:

KuPg2D.png

Fourth, specific implementation steps

Related scene description:

One day afternoon, a class teacher to inform students and teachers will want to listen to a lesson, in order to teach the quality of the teacher's score. Teachers and students began to organize related course upon receipt. Teacher during class and the class teacher by observing students look to predict the course of talking about the good or bad, the teacher observed the students frown atmosphere can be suitably adjusted curriculum, teacher observed students improve atmosphere in the classroom, give high marks. After the course, the class teacher and the teacher returned to the office, review this section of course happy together.

using a custom manner observer pattern

1. Construction of a program entity class (hereinafter both will be omitted and Setter Getter)

/**
 * 课程类
 * - 上课时间:time
 * - 上课地点:place
 * - 上课内容:content
 */
public class Course {

    private Date time;
    private String place;
    private String content;

    public Course() {
    }
    
    public Course(Date time, String place, String content) {
        this.time = time;
        this.place = place;
        this.content = content;
    }
}

2. Construction of a discoverer of abstract classes and the associated implementation class, teachers and head teachers were all inherited interface and override the relevant methods,

public abstract class Observer {
    abstract void update(Object args);
    public Observer(String identity) {
        this.identity = identity;
    }
    private String identity;
}

The teacher took the class to begin teaching:

/**
 * 老师类
 * - 观察者之一
 * - 观察学生的上课情况
 */
public class TeacherObserver extends Observer {

    private Course course;
    @Override
    public void update(Object args) {
        DateFormat df = DateFormat.getTimeInstance(DateFormat.LONG, Locale.CHINA);
        System.out.println("我是老师,正在讲课中...");
        course = new Course(new Date(), "A栋教学楼", "Java课程");
        System.out.println("今天上课时间:"+df.format(course.getTime()) + " 地点:" + course.getPlace() + " 上课内容:" + course.getContent());
    }

    public TeacherObserver(String identity) {
        super(identity);
    }
}

To teacher lectures:

/**
 * 班主任来听课
 * - 观察者之一
 * - 观察学生的上课情况
 */
public class HeadTeacherObserver extends Observer {
    @Override
    public void update(Object args) {
        System.out.println("我是班主任来听课了,正在检查课程质量...");
        System.out.println("学生反馈课程质量为:" + args);
    }

    public HeadTeacherObserver(String identity) {
        super(identity);
    }
}

This time we turn to the main body of students debut:

/**
 * 主体类
 * - 模拟被观察者主体
 */
public abstract class Subject {
    /**
     * 修改通知
     */
    abstract void doNotify();

    /**
     * 添加被观察者
     */
    abstract void addObservable(Observer o);

    /**
     * 移除被观察者
     */
    abstract void removeObservable(Observer o);
}

The student body, the object being observed:

/**
 * 学生主体
 * - 被观察的对象
 */
public class StudentSubject extends Subject {
    /**
     * 上课状态
     */
    private String state;

    private List<Observer> observableList = new ArrayList<>();

    @Override
    public void doNotify() {
        for (Observer observer : observableList) {
            observer.update(state);
        }
    }

    @Override
    public void addObservable(Observer observable) {
        observableList.add(observable);
    }

    @Override
    public void removeObservable(Observer observable) {
        try {
            if (observable == null) {
                throw new Exception("要移除的被观察者不能为空");
            } else {
                if (observableList.contains(observable) ) {
                    System.out.println("下课了,"+observable.getIdentity()+" 已回到办公室");
                    observableList.remove(observable);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Then we wait for anxious curriculum was finally scheduled to begin recording report it:

/**
 * 课程报告
 * - 一起回顾这节有意思的课
 */
public class CourseReport {
    public static void main(String[] args) {
        // 创建学生主体
        StudentSubject studentSubject = new StudentSubject();
        // 创建观察者老师
        TeacherObserver teacherObversable = new TeacherObserver("老师");
        // 创建观察者班主任
        HeadTeacherObserver headTeacherObserver = new HeadTeacherObserver("班主任");
        // 学生反映上课状态
        studentSubject.setState("(*^▽^*)讲的不错,很好,随手点个关注和在看!");
        studentSubject.addObservable(teacherObversable);
        studentSubject.addObservable(headTeacherObserver);
        // 开始上课
        studentSubject.doNotify();
        // 上课结束
        studentSubject.removeObservable(headTeacherObserver);
        studentSubject.removeObservable(teacherObversable);
    }
}

Back at the office of the teacher and the class teacher grin, students are also very satisfied with this lesson, we can see the following report reviews:

我是老师,正在讲课中...
今天上课时间:下午03时00分00秒 地点:A栋教学楼 上课内容:Java课程
我是班主任来听课了,正在检查课程质量...
学生反馈课程质量为:(*^▽^*)讲的不错,很好,随手点个关注和在看!
下课了,班主任 已回到办公室
下课了,老师 已回到办公室

② using the JDK classes implement the Observer pattern

Here we can use the JDK classes that implement the relevant observation mode, built-in viewer class has Observer interface and Observable class, use these two methods in the class can be a good observer mode is completed, and help us JDK do the relevant locking operations to ensure the security thread, the whole class would be above us improve and streamline operations.

We need major renovation of the main body of the observed and the observer realize class, as follows:

/**
 * 老师类
 * - 观察者之一
 * - 观察学生的上课情况
 */
public class TeacherObserver implements Observer {
    private Course course;
    @Override
    public void update(Observable o, Object arg) {
            DateFormat df = DateFormat.getTimeInstance(DateFormat.LONG, Locale.CHINA);
            System.out.println("我是老师,正在讲课中...");
            course = new Course(new Date(), "A栋教学楼", "Java课程");
            System.out.println("今天上课时间:"+df.format(course.getTime()) + " 地点:" + course.getPlace() + " 上课内容:" + course.getContent());
        }
}

/*************************************/

/**
 * 班主任来听课
 * - 观察者之一
 * - 观察学生的上课情况
 */
public class HeadTeacherObserver implements Observer {
    @Override
    public void update(Observable o, Object arg) {
        System.out.println("我是班主任来听课了,正在检查课程质量...");
        System.out.println("学生反馈课程质量为:" + arg);
    }
}

/*************************************/

/**
 * 学生主体
 * - 被观察的对象
 */
public class StudentObservable extends Observable {
    /**
     * 上课状态
     */
    private String state;

    public void doNotify() {
        // 设置标志
        this.setChanged();
        // 通知观察者做出相应动作
        this.notifyObservers(state);
    }
}

/*************************************/

public class CourseReport {
    public static void main(String[] args) {
        // 创建学生主体
        StudentObservable studentObservable = new StudentObservable();
        // 创建观察者老师
        TeacherObserver teacherObversable = new TeacherObserver();
        // 创建观察者班主任
        HeadTeacherObserver headTeacherObserver = new HeadTeacherObserver();
        // 学生反映上课状态
        studentObservable.setState("(*^▽^*)讲的不错,很好,随手点个关注和在看!");
        studentObservable.addObserver(teacherObversable);
        studentObservable.addObserver(headTeacherObserver);
        // 开始上课
        studentObservable.doNotify();
        // 上课结束
        studentObservable.deleteObserver(headTeacherObserver);
        studentObservable.deleteObserver(teacherObversable);
    }
}

Operating results are as follows:

我是老师,正在讲课中...
今天上课时间:下午03时00分00秒 地点:A栋教学楼 上课内容:Java课程
我是班主任来听课了,正在检查课程质量...
学生反馈课程质量为:(*^▽^*)讲的不错,很好,随手点个关注和在看!

Draw focus:

Here defines a single internal Observer method, mainly for making notification operation after the respective object to be observed:

update(Observable o, Object arg);

Method Observable class are:

addObserver (add observer), deleteObserver (delete observer), notifyObservers (wake up all observers, be brought into the argument), deleteObservers (delete all observers), setChanged (changing the flag is True), clearChanged (changing the flag is false ), hasChanged (see flag state), countObservers (count the number of observers)

Some of these methods increase the security thread synchronization mechanism to ensure that we can have associated methods require the use provided enhanced code reusability. Interested can look at the source code to achieve here is not tired described.

V. Summary

Observer pattern lets us know in the design and development time must be "multi-purpose combination, less inheritance."

We should be designed and developed for the interface becomes, not for the realization of programming.

This is a technique to create loosely coupled code. It defines subject an inter-many dependencies, when a state of the object changes, all objects that depend on it will be notified. Consisting of observers from the body and the body responsible for issuing event, at the same time observer to observe the subject by subscribing to these events. The body does not know anything of the observer, the observer knows the subject and to register callback events.

Guess you like

Origin www.cnblogs.com/charlypage/p/11707419.html