Design pattern ~ Observer ~

1.First of all

Here is a summary of the ** Observer pattern ** in the GoF design pattern.

2. What is the Observer pattern?

--The English word Observer means ** observer **. --The Observer pattern is a method that notifies the observer when the state of the observation target changes **. --The Observer pattern is useful when describing processing that responds to state changes. --The GoF design patterns are classified as ** behavioral design patterns **.

3. Sample class diagram

Observer.PNG

4. Sample program

It is a program that randomly generates numbers and displays "numbers" and "*" according to the changes.

4-1. Observer interface

An interface that represents the observer.

Observer.java


public interface Observer {
	public abstract void update(NumberGenerator generator);
}

4-2. DigitObserver class

This is a class that expresses numbers with numbers. Implement the Observer interface.

DigitObserver.java


public class DigitObserver implements Observer {

	public void update(NumberGenerator generator) {
		System.out.println("DigitObserver:" + generator.getNumber());
	}
}

4-3. GraphObserver class

This is a class that represents numbers in a simple graph. Implement the Observer interface.

GraphObserver.java


public class GraphObserver implements Observer {

	public void update(NumberGenerator generator) {
		System.out.print("GraphObserver:");
		int count = generator.getNumber();
		for (int i = 0; i < count; i++) {
			System.out.print("*");
		}
		System.out.println("");
	}
}

4-4. NumberGenerator class

An abstract class that represents an object that produces a number.

NumberGenerator.java


import java.util.ArrayList;
import java.util.Iterator;

public abstract class NumberGenerator {

	private ArrayList<Observer> observers = new ArrayList<Observer>();

	public void addObserver(Observer observer) {
		observers.add(observer);
	}

	public void deleteObserver(Observer observer) {
		observers.remove(observer);
	}

	public void notifyObservers() {
		Iterator it = observers.iterator();
		while (it.hasNext()) {
			Observer o = (Observer) it.next();
			o.update(this);
		}
	}

	public abstract int getNumber();
	public abstract void execute();
}

4-5. RandomNumberGenerator class

A class that randomly generates numbers.

RandomNumberGenerator.java


import java.util.Random;

public class RandomNumberGenerator extends NumberGenerator {

	private Random random = new Random();
	private int number;

	public int getNumber() {
		return number;
	}

	public void execute() {
		for (int i = 0; i < 10; i++) {
			number = random.nextInt(50);
			notifyObservers();
		}
	}
}

4-6. Main class

This class performs the main processing.

Main.java


public class Main {
	public static void main(String[] args) {

		NumberGenerator generator = new RandomNumberGenerator();
		Observer observer1 = new DigitObserver();
		Observer observer2 = new GraphObserver();
		generator.addObserver(observer1);
		generator.addObserver(observer2);
		generator.execute();
	}
}

4-7. Execution result

DigitObserver:35
GraphObserver:***********************************
DigitObserver:33
GraphObserver:*********************************
DigitObserver:40
GraphObserver:****************************************
DigitObserver:28
GraphObserver:****************************
DigitObserver:4
GraphObserver:****
DigitObserver:45
GraphObserver:*********************************************
DigitObserver:7
GraphObserver:*******
DigitObserver:30
GraphObserver:******************************
DigitObserver:31
GraphObserver:*******************************
DigitObserver:22
GraphObserver:**********************

5. Benefits

In the Observer pattern, the RandomNumberGenerator class that has a state, the DigitObserver class that notifies you of the state change, and the GraphObserver class appear. And what connects the two roles is the Observer interface and the NumberGenerator class. The RandomNumberGenerator class doesn't know if it's currently monitoring a DigitObserver instance or a GraphObserver instance. However, I know that the instance stored in the observers field inherits from the Observer interface and is guaranteed to be able to call the update method. On the other hand, the DigitObserver class and GraphObserver class do not know whether it is the RandomNumberGenerator instance or another XXXNumberGenerator instance that is observing itself. However, I know that it is an instance of a subclass of NumberGenerator and has a getNumber method. -** Using an abstract class or interface, pull off the abstract method from the concrete class ** -** When passing an instance as an argument or holding an instance in a field, make it an abstract class or interface type ** By doing this, you can replace the concrete class part with a click.

  1. GitHub

7. List of design patterns

-** GoF design pattern summary **

8. Reference

This article and sample program were created based on the following books.

-** Introduction to design patterns learned in Java language **

It was very easy to understand and I learned a lot. Thank you. The detailed explanations of the design patterns and sample programs are written, so please take a look at the books as well.

Recommended Posts

Design pattern ~ Observer ~
Observer Pattern
Design pattern ~ Visitor ~
Java design pattern
Design pattern ~ Proxy ~
Design pattern ~ State ~
Design pattern ~ Strategy ~
Design pattern ~ Singleton ~
Design pattern ~ Composite ~
Design pattern (2): Builder
Design pattern (1): AbstractFactory
Design pattern ~ Command ~
Design pattern ~ Iterator ~
Design pattern ~ Bridge ~
Design pattern ~ Mediator ~
Design pattern ~ Decorator ~
Design pattern ~ Prototype ~
Design pattern ~ Memento ~
Design pattern ~ Adapter ~
Design pattern ~ Flyweight ~
C ++ design pattern (TemplateMethod pattern)
Design pattern ~ Factory Method ~
Design pattern ~ Abstract Factory ~
GoF design pattern summary
Design pattern ~ Template Method ~
Java design pattern summary
PrintObserver "Observer Design Pattern: Description and Implementation Example"
Design pattern ~ Chain of Responsibility ~
[Design pattern] Java core library
Ruby design pattern template method pattern memo
C # chewed design pattern: Template Method
Application example of design pattern (No. 1)
Java beginner design pattern (Factory Method pattern)
Prototype pattern
Mediator pattern
Iterator pattern
Composite pattern
Builder pattern
Bridge Pattern
Command Pattern
Builder Pattern
Strategy pattern
Iterator Pattern
Visitor pattern
Adapter Pattern
Proxy Pattern
Strategy Pattern
Composite Pattern
Singleton Pattern
Singleton pattern
Prototype Pattern
[Design pattern] Common logic with Template Method
Facade Pattern
Decorator pattern
Flyweight Pattern
Decorator Pattern
Mediator Pattern
Facade pattern
Visitor Pattern
Bridge pattern
Java8 Lambda expression & Stream design pattern reconsideration --Command pattern -