Introducing the design patterns of [GoF](https://ja.wikipedia.org/wiki/Gang of for _ (Information Engineering)) ["Introduction to Design Patterns Learned in the Augmented and Revised Java Language"]( https://www.amazon.co.jp/ Augmented and revised edition Introduction to design patterns learned in Java language-Hiroshi Yuki / dp / 4797327030 / ref = pd_lpo_sbs_14_t_0? _ Encoding = UTF8 & psc = 1 & refRID = 2ZE4GPYNN55JGDR5QMHP) I will summarize about.
It means "observer" and means "observer". ** The pattern that notifies the observer when the state of the object to be observed changes ** is called the ** Observer pattern **. As will be described in detail later, it seems that it is sometimes called the ** Publish-Subscribe pattern ** because the observer needs to notify the observer and the observer is in a passive position. ..
The Observer pattern is used by the classes that appear in the class diagram below.
Subject This is the class to be observed. It has ʻobservers` (multiple observers) to observe itself, a method to register / delete / notify them, and a method to return its own status. As mentioned earlier, it should be noted that ** the subject, who should be the observer, holds the observer of the observer **.
Observer
This is the class that observes subject
.
Even if you say observation, you will know that the state of the observation target has changed only after being notified by the subject.
ConcreteSubject
This is the class that will be the concrete observer.
Overrides the getSubjectStatus
method that returns its own state, as declared in the parent class.
ConcreteObserveer This is the class that will be the concrete observer. Overrides the ʻupdate` method declared in the parent class to notify you that the observed state has changed.
As a concrete example, it will be explained based on the following class.
-** NumGenerator class **
NumGenerator.java
import java.util.ArrayList;
import java.util.List;
public abstract class NumGenerator {
//Holds Observer List
private List<Observer> observers = new ArrayList<>();
//Add Observer
public void addObserver(Observer observer) {
observers.add(observer);
}
//Remove observer
public void deleteObserver(Observer observer) {
observers.remove(observer);
}
//Notify Observer
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(this);
}
}
//Get the number
public abstract int getNumber();
//Generate a number(Status update)
public abstract void execute();
}
A class that serves as the Subject
of the object to be observed.
Since there can be multiple observers, we have ʻObserverin List. It also has a method for registering / deleting observers and a method for notifying registrants. The
notifyObservers method calls the ʻupdate
method for specific observers.
-** Observer class **
Observer.java
public interface Observer {
public abstract void update(NumGenerator generator);
}
This class is useful for observing NumGenerator
.
I'm declaring a ʻupdate` method to receive notifications, but I'll leave the implementation to the inheriting class.
-** RandomNumGenerator class **
RandomNumGenerator.java
import java.util.Random;
public class RandomNumGenerator extends NumGenerator {
//Random number generator
private Random random = new Random();
//Current number
private int number;
//Get the number
@Override
public int getNumber() {
return number;
}
//Generate a number(Status update)
@Override
public void execute() {
for (int i = 0; i < 10; i++) {
//Generate a random number in the range of 0 to 20 and update the current number
number = random.nextInt(21);
System.out.println("Loop count:" + (i + 1));
//Notify observer that a number has been generated
notifyObservers();
}
}
}
It is a class that inherits NumGenerator
and is a specific observation target class.
It has a field that represents a random number and the current number, and has a method to get the number and a method to generate the number.
In the method that generates a number, the loop is rotated 10 times, and in each loop, a random number is acquired within the range of 0 to 20, and the state is updated by setting the random number to the current numerical value.
It also notifies each observer with the notifyObservers
method that the state has been updated.
-** DigitObserver class **
DigitObserver.java
public class DigitObserver implements Observer {
@Override
public void update(NumGenerator generator) {
//Acquires and displays the random numbers of the observer
System.out.println("DigitObserver:" + generator.getNumber());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
Overriding the ʻupdate method in a class that serves as a concrete observer that implements the ʻObserver
.
This method describes the processing performed by the specific observer when the observation target notifies the update.
Here, the random number (current number updated) of the observation target is displayed.
-** StringObserver class **
StringObserver.java
import org.apache.commons.lang3.RandomStringUtils;
public class StringObserver implements Observer {
@Override
public void update(NumGenerator generator) {
System.out.print("StringObserver:");
//Acquires and displays a random alphabetic character string using the random number of the observer as an argument
System.out.println(RandomStringUtils.randomAlphabetic(generator.getNumber()));
System.out.println("----------------------------------------");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
Similar to DigitObserver, this class serves as a concrete observer. Here, a character string consisting of a random alphabet is displayed with the random number (current number updated) of the observation target as an argument.
-** Main class **
Main.java
public class Main {
public static void main(String[] args) {
//Generation of specific observation targets
NumGenerator generator = new RandomNumGenerator();
//Register a specific observer as a specific observation target
generator.addObserver(new DigitObserver());
generator.addObserver(new StringObserver());
//Number generation(Status update)
generator.execute();
}
}
The state is updated by generating a number after generating a specific observation target and registering a specific observer as an observation target.
The result of executing the Main
class is as follows.
You can see that the random number and the random character string for the number of digits of the random number are displayed 10 times.
Execution result
Loop count:1
DigitObserver:14
StringObserver:VNXxKnJCmkbOSG
----------------------------------------
Loop count:2
DigitObserver:15
StringObserver:FUBpVQotKbSwmMX
----------------------------------------
Loop count:3
DigitObserver:6
StringObserver:onRlXn
----------------------------------------
Loop count:4
DigitObserver:18
StringObserver:AehtMZiGkzYgapTgok
----------------------------------------
Loop count:5
DigitObserver:8
StringObserver:XuRUWXnb
----------------------------------------
Loop count:6
DigitObserver:11
StringObserver:JHYAeuMfMDO
----------------------------------------
Loop count:7
DigitObserver:12
StringObserver:sopRShHkheIO
----------------------------------------
Loop count:8
DigitObserver:11
StringObserver:BLATKGBDccR
----------------------------------------
Loop count:9
DigitObserver:18
StringObserver:kmSHMbZZftRyGkpaqa
----------------------------------------
Loop count:10
DigitObserver:15
StringObserver:muYkfeGLfwYqykD
----------------------------------------
By using the Observer pattern, it is possible to separate the class that holds the state from the class that receives notification of the change in the state, and the reusability (partization) of the class is improved.
One of the uses of the Observer pattern is the coordination of models and views in the implementation of MVC models. The model is internal data, and the controller detects changes in the state of the model (observed object) and notifies the view (observer) to cooperate.
You learned about the Observer pattern that signals changes in the state of an object. The sample code is uploaded below, so please refer to it if you like.
In addition, other design patterns are summarized below, so please refer to them as well.
-[Updated from time to time] Summary of design patterns in Java
-[Introduction to Design Patterns Learned in the Augmented and Revised Java Language](https://www.amazon.co.jp/ Introduction to Design Patterns Learned in the Augmented and Revised Java Language-Hiroshi Yuki / dp / 4797327030 / ref = pd_lpo_sbs_14_t_0? _Encoding = UTF8 & psc = 1 & refRID = 2ZE4GPYNN55JGDR5QMHP)
Recommended Posts