An in-depth analysis of the application of observer patterns in Java design pattern programming _java

Source: Internet
Author: User

definition: defines a one-to-many dependency between objects so that when each object changes state, all objects that depend on it are notified and automatically updated.
Type: behavior class pattern
class Diagram:

In software systems, there is often a need to change the state of an object, and some objects associated with it are changed accordingly. For example, we're going to design a function of a right-click menu, if you click the right mouse button in the effective area of the software, a menu pops up; for example, we want to design an automated deployment function, like eclipse development, as long as you modify the file, eclipse will automatically deploy the modified files to the server. These two functions have a similar place, that is, an object to listen to another object at all times, as long as its state changes, and then to make the corresponding action. In fact, there are many options to achieve this, but it is no doubt that the use of the observer model is a mainstream choice.

Structure of the Observer pattern
in the most basic observer model, the following four roles are included:
Observed: As you can see from the class diagram, there is a vector container in the class to hold the Observer object (the reason that vector is used instead of list is because the vector is safe while the list is unsafe for multithreading), The vector container is the core of the observed class, and there are three other methods: The Attach method is to add the Observer object to the container; The detach method is to remove the observer object from the container; The Notify method is to call the corresponding method of the observer object sequentially. This role can be an interface, an abstract class, or a specific class, because in many cases it will be mixed with other patterns, so there are more instances of using abstract classes.
Observer: The observer role is typically an interface that has only one update method, which is invoked when the observed state changes.
Specific observers: This role is used to facilitate extension, and specific business logic can be defined in this role.
Specific Observer: the concrete implementation of the Observer interface, in which the logic to be dealt with when the observed object's state changes is defined.

Observer Pattern Implementation Example
Subject Interface

Public interface Subject {public
  void Registerobserver (Observer o);
  public void Removeobserver (Observer o);
  public void Notifyallobservers ();
}

Observer interface

Public interface Observer {public
  void update (Subject s);
}

The Hunter class implements the subject interface

Import java.util.ArrayList;
 
public class Headhunter implements subject{
 
  //define a list of users, such as Mike, Bill, etc.
  Private arraylist<observer> userlist;
  Private arraylist<string> jobs;
 
  Public Headhunter () {
    userlist = new arraylist<observer> ();
    Jobs = new arraylist<string> ();
  }
 
  @Override public
  void Registerobserver (Observer o) {
    userlist.add (o);
  }
 
  @Override public
  void Removeobserver (Observer o) {}
 
  @Override public
  void Notifyallobservers () {
    for (Observer o:userlist) {
      o.update (this);
    }
  }
 
  public void AddJob (String job) {
    this.jobs.add (job);
    Notifyallobservers ();
  }
 
  Public arraylist<string> Getjobs () {return to
    jobs;
  }
 
  Public String toString () {return
    jobs.tostring ();
  }
}

Jobseeker is an observer:

public class Jobseeker implements Observer {
 
  private String name;
 
  Public jobseeker (String name) {
    this.name = name;
  }
  @Override public
  void Update (Subject s) {
    System.out.println (this.name + "got notified!");
    Print job list
    System.out.println (s);
  }
}

To start using:

public class Main {public
  static void Main (string[] args) {
    headhunter hh = new Headhunter ();
    Hh.registerobserver (New Jobseeker ("Mike"));
    Hh.registerobserver (New Jobseeker ("Chris"));
    Hh.registerobserver (New Jobseeker ("Jeff"));
 
    Every time you add a job, all job-seeking people are notified.
    hh.addjob ("Google Job");
    Hh.addjob ("Yahoo Job");
  }


The advantages of the

Observer pattern
        The Observer and the observed are mildly correlated and abstract coupled so that It's easier for both to expand. The
        Observer pattern is a commonly used trigger mechanism that forms a chain of triggers, which in turn deals with the methods of each observer. But at the same time, this is a disadvantage of the observer model, because it is a chain trigger, when the observer is more, the performance problem is more worrying. Moreover, in the chain structure, it is easy to appear circular reference errors, resulting in the system suspended animation.
 
Summary
       Java language, there is an interface observer, As well as its implementation class observable, the observer role is often implemented. We can see how these two classes are used in the JDK API documentation.
       friends who have done VC + +, JavaScript dom, or AWT development are amazed by their event handling, understanding the Observer pattern, There is a certain understanding of the principle of the event handling mechanism. If you want to design an event-triggering mechanism, it is a good choice to use the observer pattern, and the event-handling Dem (Delegate event model delegation) in AWT is implemented using the Observer pattern.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.