Behavioral model of design model (observer model)

Introduction – send status change notification
Observer pattern is a behavior design pattern that allows you to define a subscription mechanism that can notify multiple other objects that "observe" the object when an object event occurs.

Sample program
The observer will observe an object that generates numerical values and display the numerical results it generates. The display mode of different observers is different. DigitObserver will display the value in digital form, while graphoberver will display the value in simple graphical form.

List of classes and interfaces:

  • Observer: observer interface
  • NumberGenerator: abstract class of the object that generates the value
  • RandomNumberGenerator: a class that generates random numbers
  • DigitObserver: a class that displays numeric values in numeric form
  • Graphoberver: a class that displays numeric values in simple graphical form
  • Main: the class of the test program

Class diagram:

Observer: the interface of the observer. The specific observer will implement this interface

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

NumberGenerator: abstract class of the object that generates the value

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

public abstract class NumberGenerator {
    private ArrayList observers = new ArrayList();//Save observers
    public void addObserver(Observer observer) {//Register Observer
        observers.add(observer);
    }
    public void deleteObserver(Observer observer) {//Delete Observer
        observers.remove(observer);
    }
    public void notifyObservers() {	//Send notifications to observers
        Iterator iterator = observers.iterator();
        while (iterator.hasNext()) {
            Observer o = (Observer) iterator.next();
            o.update(this);
        }
    }
    public abstract int getNumber();//Get value
    public abstract void execute();//Generate value
}

RandomNumberGenerator: a class that generates random numbers

import java.util.Random;

public class RandomNumberGenerator extends NumberGenerator {
    private Random random = new Random();
    private int number;
    @Override
    public int getNumber() {
        return number;
    }

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

DigitObserver: a class that displays numeric values in numeric form

public class DigitObserver implements Observer{
    @Override
    public void update(NumberGenerator generator) {
        System.out.println("DigitObserver:" + generator.getNumber());
        try {
            Thread.sleep(100);		// In order to let you see how it generates values, sleep is used to reduce the running speed of the program
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Graphoberver: a class that displays numeric values in simple graphical form

public class GraphObserver implements Observer{
    @Override
    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("");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Main: the class of the test program

public class Main {
    public static void main(String[] args) {
        RandomNumberGenerator generator = new RandomNumberGenerator();
        DigitObserver observer1 = new DigitObserver();
        GraphObserver observer2 = new GraphObserver();
        generator.addObserver(observer1);
        generator.addObserver(observer2);
        generator.execute();
    }
}

Role:

  • The Subject role defines methods for registering and deleting observers. The method of "get current state" is also declared. The NumberGenerator class in the sample program plays this role
  • Contretesubject (specific observation object) will notify all registered Observer roles when its status changes. The RandomNumberGenerator class in the sample program plays this role
  • The Observer is responsible for receiving the notification of the status change from the Subject role and declares the update method. In the sample program, the Observer interface plays this role
  • Contreobserver (specific observer) returns to get the latest state of the object to be observed after its update method is called. The DigitObserver class and graphoberver class in the sample program play this role

Observer mode is suitable for application scenarios

  • Observer mode can be used when the change of the state of an object needs to change other objects, or the actual object is unknown or dynamically changed in advance.
  • This mode can be used when some objects in the application must observe other objects.

Tags: Java Design Pattern

Posted on Sat, 27 Nov 2021 22:27:12 -0500 by johnska7