Java built-in observer pattern
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(); } }

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
