Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to implement the Observer pattern in java

Shulou Source: shulou.com Published: 2022-06-02 10:13:15 10月05日 Update

This article is about how to achieve the observer mode in java. I think it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it.

Public class Teacher extends Observable {private String content; public void setHomework (final String content) {this.content = content; System.out.println ("the assignment is:" + content); / * * Mark that the object has been changed before you can notify * / setChanged () / * notify the observer that the observer update method * / notifyObservers () will be called;} public String getContent () {return this.content;}} public class Student implements Observer {private final Observable observable; private final String name; public Student (Observable observable, String name) {this.observable = observable; this.name = name Observable.addObserver (this);} @ Override public void update (Observable o, Object arg) {if (o instanceof Teacher) {Teacher teacher = (Teacher) o; System.out.println (name + "get job information:" + teacher.getContent ()) } public class Test {public static void main (String [] args) {/ * instance observable * / Teacher teacher = new Teacher (); Student S1 = new Student (teacher, "Zhang San"); Student S2 = new Student (teacher, "Li Si"); Student S3 = new Student (teacher, "Wang Wu") Teacher.setHomework ("question 6 on page 2"); teacher.setHomework ("question 7 on page 3"); teacher.setHomework ("question 8 on page 5");}}

Output information:

The above is how to implement the observer mode in java. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Tags: Observers observations patterns information more knowledge articles assignments practical objects that is work meetings articles methods tags look knowledge points industries details information Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS vpn MariaDB Huawei Shulou Information