The Observer pattern is a design pattern that allows objects to subscribe to event notifications and automatically respond when events occur. In Java, it is usually implemented using the Observable (Subject) and Observer (Observer) interfaces, where the subject maintains a collection of observers and notifies them when changes occur. The Observer pattern provides the advantages of loose coupling, scalability, and efficient notifications and is widely used in the following scenarios: event-driven programming, GUI updates, and Pub/Sub systems.
In-depth analysis of the observer pattern of Java design patterns
Introduction
The observer pattern is a design Pattern that allows objects to subscribe to event notifications to automatically respond when an event occurs. In this way, observers can receive updates from topics or publishers without explicitly polling.
Implementation method
The observer pattern in Java usually uses the following interface:
-
Observable
(topic) : Defines methods for observer registration, unregistration and notification. -
Observer
(Observer): Defines the update method, which will be called when the observed object changes.
In practical applications, subjects usually implement the Observable
interface, while observers implement the Observer
interface. The topic maintains a collection of observers and notifies them by calling the observer's update
method.
Practical Case
Suppose we have a stock market application that needs to monitor stock prices in real time. We can use the observer pattern to achieve this functionality.
Topic: Stocks
public class Stock implements Observable { private List<Observer> observers; private double price; public Stock() { observers = new ArrayList<>(); } @Override public void addObserver(Observer observer) { observers.add(observer); } @Override public void deleteObserver(Observer observer) { observers.remove(observer); } @Override public void notifyObservers() { for (Observer observer : observers) { observer.update(this); } } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; notifyObservers(); } }
Observer: Stock Price Display
public class StockPriceDisplay implements Observer { private Stock stock; public StockPriceDisplay(Stock stock) { this.stock = stock; stock.addObserver(this); } @Override public void update(Observable observable) { double price = stock.getPrice(); System.out.println("Current stock price: " + price); } }
Example Usage
In the example usage, we create a stock object and register an observer to monitor its price:
Stock stock = new Stock(); StockPriceDisplay display = new StockPriceDisplay(stock); // 设置股票价格,这将自动触发观察者更新 stock.setPrice(100.0);
Advantages
The observer pattern provides Some advantages:
- Loose coupling: Communication between observers and topics is loosely coupled, allowing modifications without affecting each other.
- Extensibility: It is easy to add and remove observers without modifying the theme's implementation.
- Notification efficiency: When a topic changes, the observer pattern efficiently propagates updates to all subscribers.
Application scenarios
The observer mode is widely used in various scenarios, such as:
- Monitoring system
- Event Driven Programming
- GUI Update
- Pub/Sub System
The above is the detailed content of Java Design Patterns Observer Pattern Deep Dive. For more information, please follow other related articles on the PHP Chinese website!

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.