Observer pattern
The Observer Pattern is a behavioral design pattern that defines a one-to-many dependency in which, when an object's state changes, all its dependents are notified and updated automatically.
When a one-to-many relationship exists between objects, the Observer Pattern is used. For example, when an object is modified, the objects that depend on it are automatically notified. The Observer Pattern belongs to behavioral patterns.
Introduction
Intent
Creates a one-to-many dependency between objects, so that when an object's state changes, all objects that depend on it are notified and updated automatically..
Main problem solved
- The Observer Pattern solves the problem of how to automatically notify other dependent objects when an object's state changes, while maintaining low coupling and high collaboration between objects.
Use Cases
- When a change in one object's state requires other objects to be updated at the same time.
Implementation
- Define the observer interface: Contains an update method.
- Create the concrete observer: Implements the observer interface and defines the behavior when a notification is received.
- Define the subject interface: Contains methods for adding, deleting, and notifying observers.
- Create the concrete subject: Implements the subject interface, manages the observer list, and notifies them when the state changes.
Key code
- Observer list: An observer list is maintained in the subject.
Application Example
- Auction system: The auctioneer acts as the subject and the bidders as observers; when the auction price is updated, all bidders are notified.
- Journey to the West story: The Bodhisattva sprinkling water is the state change, and the old turtle is the observer that observes this change.
Advantages
- Abstract coupling: The observer and the subject are abstractly coupled.
- Trigger mechanism: Establishes a set of trigger and notification mechanisms for state changes.
Disadvantages
- Performance Issues: If there are many observers, the notification process may be time-consuming.
- Circular dependency: May cause circular calls and system crashes.
- Lack of change details: The observer does not know how the subject changed, only that a change occurred.
Usage recommendation
- Use when there is a need to reduce coupling between objects and when state changes in one object need to trigger changes in others.
- Consider using Java's built-in Observer Pattern support classes, such as
java.util.Observableandjava.util.Observer。
Notes
- Avoid circular references: Pay attention to the dependency between observers and the subject, avoiding circular references.
- asynchronous: Consider using asynchronous notification to avoid a single point of failure causing the whole system to stall.
structures
The Observer Pattern contains the following core roles:
- Subject (Subject): Also known as the observed or observable, it is an object with state and maintains a list of observers. The subject provides methods to add, delete, and notify observers.
- Observer (Observer): The observer is the object that receives notifications from the subject. The observer needs to implement an update method, which is called to perform the update operation when a notification from the subject is received.
- Concrete Subject (Concrete Subject): The concrete subject is the concrete implementation class of the subject. It maintains the observer list and notifies observers when the state changes.
- Concrete Observer (Concrete Observer): The concrete observer is the concrete implementation class of the observer. It implements the update method and defines the specific operations to be performed when a notification from the subject is received.
The Observer Pattern achieves loose coupling between objects by decoupling the subject and observers. When the subject's state changes, all observers that depend on it are notified and perform the corresponding updates.
Create a class that implements
The Observer Pattern uses three classes: Subject, Observer, and Client. The Subject object has methods to bind observers to and unbind observers from the Client object. We create Subject class,Observer abstract class and the entity class that extends the abstract class Observer .
ObserverPatternDemo, and our demo class uses the Subject and use the entity class object to demonstrate the Observer Pattern.
Step 1
Create the Subject class.
Subject.java
import
java
.
util
.
ArrayList
;
import
java
.
util
.
List
;
public
class
Subject
{
private
List
<
Observer
observers
=
new
ArrayList
<
Observer
(
);
private
int
state
;
public
int
getState
(
)
{
return
state
;
}
public
void
setState
(
int
state
)
{
this
.
state
=
state
;
notifyAllObservers
(
)
;
}
public
void
attach
(
Observer
observer
)
{
observers
.
add
(
observer
)
;
}
public
void
notifyAllObservers
(
)
{
for
(
Observer
observer
:
observers
)
{
observer
.
update
(
)
;
}
}
}
Step 2
Create the Observer class.
Observer.java
public
abstract
class
Observer
{
protected
Subject
subject
;
public
abstract
void
update
(
)
;
}
Step 3
Create the concrete observer class.
BinaryObserver.java
public
class
BinaryObserver
extends
Observer
{
public
BinaryObserver
(
Subject
subject
)
{
this
.
subject
=
subject
;
this
.
subject
.
attach
(
this
)
;
}
@
Override
public
void
update
(
)
{
System
.
out
.
println
(
"
Binary String:
"
Integer
.
toBinaryString
(
subject
.
getState
(
)
)
)
;
}
}
OctalObserver.java
public
class
OctalObserver
extends
Observer
{
public
OctalObserver
(
Subject
subject
)
{
this
.
subject
=
subject
;
this
.
subject
.
attach
(
this
)
;
}
@
Override
public
void
update
(
)
{
System
.
out
.
println
(
"
Octal String:
"
Integer
.
toOctalString
(
subject
.
getState
(
)
)
)
;
}
}
HexaObserver.java
public
class
HexaObserver
extends
Observer
{
public
HexaObserver
(
Subject
subject
)
{
this
.
subject
=
subject
;
this
.
subject
.
attach
(
this
)
;
}
@
Override
public
void
update
(
)
{
System
.
out
.
println
(
"
Hex String:
"
Integer
.
toHexString
(
subject
.
getState
(
)
)
.
toUpperCase
(
)
)
;
}
}
Step 4
Use Subject and the concrete observer object.
ObserverPatternDemo.java
public
class
ObserverPatternDemo
{
public
static
void
main
(
String
[
]
args
)
{
Subject
subject
=
new
Subject
(
)
;
new
HexaObserver
(
subject
)
;
new
OctalObserver
(
subject
)
;
new
BinaryObserver
(
subject
)
;
System
.
out
.
println
(
"
First state change: 15
"
)
;
subject
.
setState
(
15
)
;
System
.
out
.
println
(
"
Second state change: 10
"
)
;
subject
.
setState
(
10
)
;
}
}
Step 5
Run the program, output result:
First state change: 15
Hex String: F
Octal String: 17
Binary String: 1111
Second state change: 10
Hex String: A
Octal String: 12
Binary String: 1010