Observer pattern in Java

Introduction

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.

Observer pattern

What is Observer

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. ..

Character

The Observer pattern is used by the classes that appear in the class diagram below. image.png

Abstract class

Implementation class

Concrete example

As a concrete example, it will be explained based on the following class. image.png

Abstract 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. ThenotifyObservers 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.

Implementation 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.

Execution class

-** 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.

Execution result

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

merit

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.

Where to use

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.

Summary

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.

-Observer sample code

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

References

-[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

Observer pattern in Java
Facade pattern in Java
Singleton pattern in Java
Flyweight pattern in Java
Iterator pattern in Java
Decorator pattern in Java
Prototype pattern in Java
Proxy pattern in Java
Template Method pattern in Java
Chain of Responsibility pattern in Java
Design Pattern #Observer
Learn the design pattern "Observer" in Python
Singleton pattern in Python
Linux permissions in Java
Use DataFrame in Java
Visitor pattern in Python
Sample source of Observer pattern realized by Java, PHP, Python
Implement Table Driven Test in Java
Detect and process signals in Java.
Observer pattern understood by cats Part 1
Implement the Singleton pattern in Python
Implemented bubble sort in Java (BubbleSort)
Observer pattern understood by Nyanko Part 2
GoF java design pattern rough summary
Overlapping regular expressions in Python and Java
Learn the design pattern "Prototype" in Python
Learn the design pattern "Builder" in Python
Learn the design pattern "Flyweight" in Python
Learn the design pattern "Memento" in Python
Learn the design pattern "Proxy" in Python
Express Python yield in JavaScript or Java
Apply Google Java Style formatter in IntelliJ
Learn the design pattern "Command" in Python
Differences in syntax between Python and Java
Get mail using Gmail API in Java
Learn the design pattern "Visitor" in Python
Learn the design pattern "Bridge" in Python
Learn the design pattern "Mediator" in Python
Learn the design pattern "Decorator" in Python
Learn the design pattern "Iterator" in Python
Learn the design pattern "Strategy" in Python
Learn the design pattern "Composite" in Python
Learn the design pattern "State" in Python
Let's run a Bash script in Java
Learn the design pattern "Adapter" in Python
[Gang of Four] Design pattern learning --Observer