Home  >  Article  >  Java  >  Specific analysis of the observer pattern in Java design patterns

Specific analysis of the observer pattern in Java design patterns

黄舟
黄舟Original
2017-08-10 09:32:041257browse

This article introduces the observer pattern of traffic java design pattern, which defines a one-to-many dependency relationship between objects so that when each object changes state. The following is an introduction to the observer pattern of Java design patterns through class diagrams and example codes. Friends who are interested should take a look.

Definition: Define a one-to-many dependency relationship between objects, so that when each When an object changes state, all objects that depend on it are notified and updated automatically.

Type: Behavioral class pattern

Class diagram:

## In software systems, there is often such a requirement: if an object When the state changes, some objects related to it must also make corresponding changes. For example, we want to design a right-click menu function. As long as you right-click the mouse within the valid area of ​​the software, a menu will pop up; for another example, we want to design an automatic deployment function, just like when developing eclipse, as long as the file is modified , eclipse will automatically deploy the modified files to the server. These two functions have a similarity, that is, one object must monitor the other object at all times, and as soon as its status changes, it must take corresponding actions. In fact, there are many solutions that can achieve this, but there is no doubt that using the observer mode is a mainstream choice.

The structure of the observer pattern

In the most basic observer pattern, it includes the following four roles:

  •  Observed: As you can see from the class diagram, the class has a Vector container used to store observer objects (the reason why Vector is used instead of List is because during multi-threaded operations, Vector (is safe, while List is unsafe), this Vector container is the core of the observer class, and there are three other methods: the attach method is to add an observer object to this container; the detach method is to remove it from the container In addition to the observer object; the notify method is to call the corresponding method of the observer object in sequence. This role can be an interface, an abstract class, or a concrete class. Because it is often mixed with other patterns, abstract classes are often used.

  •  Observer: The observer role is generally an interface, which has only one update method. This method will be triggered and called when the state of the observer changes.

  •  Specific observer: This role is used to facilitate expansion, and specific business logic can be defined in this role.

  •  Specific observer: A specific implementation of the observer interface. In this role, the logic to be processed when the state of the observed object changes will be defined.

Observer pattern code implementation


abstract class Subject { 
  private Vector<Observer> obs = new Vector<Observer>(); 
  public void addObserver(Observer obs){ 
    this.obs.add(obs); 
  } 
  public void delObserver(Observer obs){ 
    this.obs.remove(obs); 
  } 
  protected void notifyObserver(){ 
    for(Observer o: obs){ 
      o.update(); 
    } 
  } 
  public abstract void doSomething(); 
} 
class ConcreteSubject extends Subject { 
  public void doSomething(){ 
    System.out.println("被观察者事件反生"); 
    this.notifyObserver(); 
  } 
} 
interface Observer { 
  public void update(); 
} 
class ConcreteObserver1 implements Observer { 
  public void update() { 
    System.out.println("观察者1收到信息,并进行处理。"); 
  } 
} 
class ConcreteObserver2 implements Observer { 
  public void update() { 
    System.out.println("观察者2收到信息,并进行处理。"); 
  } 
} 
public class Client { 
  public static void main(String[] args){ 
    Subject sub = new ConcreteSubject(); 
    sub.addObserver(new ConcreteObserver1()); //添加观察者1 
    sub.addObserver(new ConcreteObserver2()); //添加观察者2 
    sub.doSomething(); 
  } 
}

Running results

Observed event reflection

Observer 1 receives the information and processes it.

Observer 2 receives the information and processes it.

We can see from the running results that we only called the Subject method, but at the same time the related methods of the two observers were called at the same time. Take a closer look at the code. It is actually very simple. It is nothing more than associating the Observer class in the Subject class and traversing the Observer's update method in the doSomething method.


Advantages of the observer pattern
## There is a slight relationship between the observer and the observed , and are abstractly coupled, making it easier for both to extend.


The observer pattern is a commonly used trigger mechanism. It forms a trigger chain and processes the methods of each observer in turn. But at the same time, this is also a shortcoming of the observer mode. Because it is a chain trigger, when there are many observers, performance issues are more worrying. Moreover, in the chain structure, it is easier for circular reference errors to occur, causing the system to freeze.


Summary
In the Java language, there is an interface Observer, and its implementation class Observable, for observers Roles are often realized. We can check the usage of these two classes in the jdk api documentation.


Friends who have done VC++, JavaScript DOM or AWT development are amazed by their event processing. Once you understand the observer pattern, you will have a certain understanding of the principles of the event processing mechanism. If you want to design the function of an event triggering processing mechanism, using the observer pattern is a good choice. The event processing DEM (Delegation Event Model) in AWT is implemented using the observer pattern.

The above is the detailed content of Specific analysis of the observer pattern in Java design patterns. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn