Concept
The observer pattern is also called publish-subscribe pattern. It is a one-to-many relationship between objects. When the state of an object changes , all objects that depend on it are notified and automatically updated
Composition
Abstract theme role (Subject
)
Also called abstract target class, the abstract subject knows which observers it has, and provides methods to delete and add observers and abstract methods to notify observers , which are determined by abstract classes or Interface implementation
Abstract Observer role (Observer
)
contains an updated abstract method, called when receiving an update notification from a specific subject, implemented by an abstract class or interface
Concrete subject role (Concrete Subject
)
Also called the specific target class, it implements the notification method of the abstract target class. When the specific topic changes, it notifies all observers who subscribe to itself
Specific Observer role (Concrete Observer
)
Abstract method to implement the abstract observer role, Change its own status after receiving the topic change notification
Implementation
Abstract ObserverObserver
Interface
Contains an observer method to receive notifications and change its own status
public interface Observer { //收到通知,改变自身状态 void update(); }
Specific observersObserverOne
and ObserverTwo
Implement the update method in the Observer interface
public class ObserverOne implements Observer{ @Override public void update() { System.out.println("第一个观察者收到通知,状态更新了"); } }
public class ObserverTwo implements Observer { @Override public void update() { System.out.println("第二个观察者收到通知,状态更新了"); } }
Subject
Interface
Contains methods to add, delete, and notify observers, It is implemented by the abstract target class, and there is also a method of its own operation, which is implemented by the specific target class
public interface Subject { //添加观察者 void add(Observer observer); //删除观察者 void remove(Observer observer); //通知所有观察者 void notifyObservers(); //自身操作 void operation(); }
Abstract target classAbstractSubject
Abstract class , because the number of observers is not fixed, use Vector dynamic array to store observers and implement the add, remove, notifyObservers methods in the Subject interface. The operation method is implemented by the specific target class
public abstract class AbstractSubject implements Subject{ Vector<Observer> vector = new Vector<Observer>(); @Override public void add(Observer observer){ vector.add(observer); } @Override public void remove(Observer observer){ vector.remove(observer); } @Override public void notifyObservers(){ for (Observer observer : vector) { observer.update(); } } }
Specific target classMySubject
Inherit the AbstractSubject class, implement the operation method, and call the notifyObservers method in the operation method to Achieve the effect of notifying observers after its own state changes
public class MySubject extends AbstractSubject{ @Override public void operation() { System.out.println("具体目标状态改变"); System.out.println("正在通知观察者。。。"); notifyObservers(); System.out.println("通知完毕!"); } }
Test classTest
public class Test { public static void main(String[] args) { MySubject mySubject = new MySubject(); mySubject.add(new ObserverOne()); mySubject.add(new ObserverTwo()); mySubject.operation(); } }
Summary
What problems does the observer pattern mainly solve
Under low coupling conditions, when the state of an object changes, other objects will receive notifications
When to use the observer pattern
When the state of an object changes, all dependent objects will receive broadcast notifications
Advantages of the observer pattern
The observer and the target are abstractly coupled, low coupling, and a set of trigger mechanisms
Disadvantages of the observer pattern
-
①If there are many direct observers and indirect observers that depend on a target, it will take a lot of time to notify all observers
②If there are many direct observers and indirect observers in a target If there are cyclic dependencies, cyclic calls may occur, causing the system to crash
-
③The observer cannot know how the target state changes, only that the target state has changed
Notes on the Observer Pattern
①There are already support classes for the Observer Pattern in JAVA and can be used directly
②Avoid circular calls
③If the update method of the observer is executed sequentially, an observer error will cause the system to get stuck. Generally, asynchronous is used Way.
The above is the detailed content of How to implement observer pattern in JAVA. 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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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),

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment