How to implement observer pattern in JAVA
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!

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

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

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
