I have briefly written a small example of the observer pattern (also known as the publish-subscribe pattern) before, and this pattern is also commonly used in projects now. Today I’ll post how to use Java’s built-in observer pattern.
The main Java APIs used are two classes:
Observer interface: Observer object, which monitors data changes of the observed object. Once the data changes, it will respond accordingly.
Observable class: Observable object, provides methods to add and remove observer objects, and notifies all added observer objects when the data is completed.
Observer code example:
//Observable是被观察者对象接口,实现该接口就是:目标(被观察者)的具体实现 public class TargetObservable extends Observable { // 要观察的数据:消息发生改变时,所有被添加的观察者都能收到通知 private String message; public String getConent() { return message; } public void setMessage(String message) { this.message = message; // 被观察者数据发生变化时,通过以下两行代码通知所有的观察者 this.setChanged(); this.notifyObservers(message); } }
2 observer code examples:
//Observer对象是观察者,实现Observer的对象就是具体的观察者对象 public class TargetObserver implements Observer { // 定义观察者名称 private String name; public String getObserverName() { return name; } public void setObserverName(String observerName) { this.name = observerName; } @Override public void update(Observable arg0, Object arg1) { //更新消息数据 System.out.println(name + "收到了发生变化的数据内容是:" + ((TargetObservable) arg0).getConent()); } }
public class TargetObserver01 implements Observer { // 定义观察者名称 private String name01; public String getObserverName() { return name01; } public void setObserverName(String observerName) { this.name01 = observerName; } @Override public void update(Observable arg0, Object arg1) { //更新消息数据 System.out.println(name01 + "收到了发生变化的数据内容是:" + ((TargetObservable) arg0).getConent()); } }
Test code:
public static void main(String[] args) { // 创建一个具体的被 观察者 TargetObservable observable = new TargetObservable(); // 创建第一个观察者 TargetObserver one = new TargetObserver(); one.setObserverName("我是观察者A"); // 创建第二个观察者 TargetObserver01 two = new TargetObserver01(); two.setObserverName("我是观察者B"); // 注册观察者 observable.addObserver(one); observable.addObserver(two); // 目标更新天气情况 observable.setMessage("***我要更新的数据***"); } }
Execution result:
I am observer B and received the changed data content: —–I want to update Data————
I am an observer A. I have received the changed data. The content is:————The data I want to update————
Advantages of the mode:
One observer can correspond to multiple observers. When the observed changes At that time, he can notify the message to all added observers. Interface-based implementation provides greater flexibility for programs.
But when using it, be careful to add or remove observer objects in time according to conditions, otherwise it may lead to unexpected results.
Finally, attach the original code of Observer and Observable, so that we know how to start when writing:
package java.util; import java.util.Observable; public interface Observer { void update(Observable var1, Object var2); }
package java.util; import java.util.Observer; import java.util.Vector; public class Observable { private boolean changed = false; private Vector<Observer> obs = new Vector(); public Observable() { } public synchronized void addObserver(Observer var1) { if(var1 == null) { throw new NullPointerException(); } else { if(!this.obs.contains(var1)) { this.obs.addElement(var1); } } } public synchronized void deleteObserver(Observer var1) { this.obs.removeElement(var1); } public void notifyObservers() { this.notifyObservers((Object)null); } public void notifyObservers(Object var1) { Object[] var2; synchronized(this) { if(!this.changed) { return; } var2 = this.obs.toArray(); this.clearChanged(); } for(int var3 = var2.length - 1; var3 >= 0; --var3) { ((Observer)var2[var3]).update(this, var1); } } public synchronized void deleteObservers() { this.obs.removeAllElements(); } protected synchronized void setChanged() { this.changed = true; } protected synchronized void clearChanged() { this.changed = false; } public synchronized boolean hasChanged() { return this.changed; } public synchronized int countObservers() { return this.obs.size(); } }

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.