Detailed explanation of Observer mode

Detailed explanation of Observer mode

The relationship between data in Excel and line chart, pie chart and column chart; The relationship between model and view in MVC mode; Event source and event handler in the event model. All this is very convenient if implemented in observer mode.

Definition and characteristics of pattern

The definition of Observer mode: it means that there is a one to many dependency between multiple objects. When the state of an object changes, all objects that depend on it are notified and automatically updated. This mode is sometimes called publish subscribe mode and model view mode. It is an object behavior mode.

Observer mode is an object behavior mode, and its main advantages are as follows.

  1. It reduces the coupling relationship between the target and the observer, which is an abstract coupling relationship. Comply with the principle of dependency inversion.
  2. A trigger mechanism is established between the target and the observer.

Its main disadvantages are as follows.

  1. The dependency between the target and the observer is not completely removed, and circular references may occur.
  2. When there are many observers, the announcement takes a lot of time, which affects the efficiency of the program.

Structure and implementation of pattern

When implementing observer mode, it should be noted that the specific target object and the specific observer object cannot be called directly, otherwise they will be closely coupled, which violates the object-oriented design principle.

  1. Pattern structure

The main roles of the observer model are as follows.

  1. Abstract Subject role: also known as abstract target class, it provides an aggregation class for saving observer objects, methods for adding and deleting observer objects, and abstract methods for notifying all observers.
  2. Concrete Subject role: also known as concrete target class, it implements the notification method in the abstract target. When the internal state of the Concrete Subject changes, it notifies all registered observer objects.
  3. Abstract Observer role: it is an abstract class or interface, which contains an abstract method to update itself. It is called when receiving the change notification of a specific topic.
  4. Concrete Observer role: implement the abstract method defined in the abstract observer to update its status when notified of the change of the target.

Application scenario of pattern

In a software system, when one party's behavior depends on the change of the other party's behavior, the observer mode can be used to loosely couple the two sides, so that the change of one party can be notified to the interested object of the other party, so that the object of the other party can respond to it.

Through the previous analysis and application examples, it can be seen that the observer mode is suitable for the following situations.

  1. There is a one to many relationship between objects. The change of the state of one object will affect other objects.
  2. When an abstract model has two aspects, one of which depends on the other, they can be encapsulated in independent objects so that they can be changed and reused independently.
  3. To realize the function similar to the broadcast mechanism, you don't need to know the specific listener, you just need to distribute the broadcast, and the interested objects in the system will automatically receive the broadcast.
  4. Multi level nesting is used to form a chain trigger mechanism, so that events can be notified across domains (across two observer types).

Mode extension

In Java, through Java util. Observable (obsolete in Java 9) class and Java util. The observer (obsolete in Java 9) interface defines observer patterns. As long as their subclasses are implemented, observer pattern instances can be written.

Override: PropertyChangeListener

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

class EventSource {
    private String name;
    /**
     * Add a PropertyChangeSupport object at the event source, which is indirectly responsible for adding listening and firing events
     */
    private PropertyChangeSupport listeners =new PropertyChangeSupport(this);

    /**
     *
     * Adding a listener on the event source is actually adding a listener on the PropertyChangeSupport object
     */
    public void addListener(PropertyChangeListener listener) {
        listeners.addPropertyChangeListener(listener);
    }
    /**
     *
     * ditto
     */
    public void removeListener(PropertyChangeListener listener) {
        listeners.removePropertyChangeListener(listener);
    }
    public String getName() {
        return name;
    }

    /**
     * When the event source changes, the event is also sent to the listener through the PropertyChangeSupport object
     */
    public void setName(String name) {
        this.name = name;
        // Trigger the event source, and the listener gets the trigger change
        listeners.firePropertyChange(null,null,getName());
    }
}

class  Monitor implements PropertyChangeListener{
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        System.out.println("The event source has changed, please handle it accordingly!");
    }
}

public class TestPropertyChangeSupport {
    public static void main(String[] args) {
        EventSource eventSource = new EventSource();
        Monitor monitor = new Monitor();
        //Add a listener on the event source, and the propertyChange method will be called when changes occur
        eventSource.addListener(monitor);

        eventSource.setName("change name Attribute value");
    }
}

Listener pattern applicationlister in Spring

@Service
public class OrderService {
 /*   public  void makeOrder(){
        System.out.println("1.............Create order "");
        System.out.println("2.............Send SMS "");
        System.out.println("3.............Send mail "");
        System.out.println("4.............Send station information "");
    }*/

    @Autowired
    private ApplicationContext applicationContext;
    public  void makeOrder() {
        //1: Create an order - the main responsibilities are to create an order, meet the requirements, the principle of single responsibility and the principle of opening and closing
        System.out.println("1.............Create order");
        //Events related to publishing orders
        applicationContext.publishEvent(new OrderEvent(applicationContext));
    }
}
//Order event
public class OrderEvent extends ApplicationEvent {
    public OrderEvent(Object source) {
        super(source);
    }
}

//monitor
@Component
public class SmsListener implements ApplicationListener<OrderEvent> {

    @Override
    public void onApplicationEvent(OrderEvent event) {
        System.out.println("Sms.............Message sent successfully");
    }
}

//monitor
@Component
public class EmailLinstener implements ApplicationListener<OrderEvent> {

    @Override
    public void onApplicationEvent(OrderEvent event) {
        System.out.println("Email.............Message sent successfully");
    }
}

Keywords: Java Design Pattern

Added by Flinch on Sat, 08 Jan 2022 19:36:41 +0200