Design Pattern-Observer Pattern

Source: Internet
Author: User

Design Pattern-Observer Pattern

Do you still remember "refresh" in the right-click menu of Windows? After a file is transmitted to a directory through FPT, You need to manually refresh the file window to see the file. This problem does not exist in Linux. Before answering the questions, let's take a look at observer mode.

Observer mode:Defines a one-to-many dependency, allowing multiple observer objects to listen to a topic object at the same time. When the status of this topic object changes, it notifies all observer objects so that they can automatically update themselves.

Role involved in the mode (object type ):

Topic (Subject ):It saves the reference of all observer objects to one aggregation, and each topic can have any number of observers. The topic provides an interface to add and delete observer objects. When a specific topic changes its internal status, it sends a notification to all registered observers, pushes the status to the observer, or notifies the observer to pull the desired information. Observer (Observer ):Define an interface for all the observers and update themselves when receiving the topic notification. Class diagram of the observer mode: vcC0v7S/tM7EvP7Ptc2z0 + vOxLz + release/s + release + t6LJ + rHku6 + jqLG7yb6z/aGiu/release + release = "http://www.2cto.com/uploadfile/Collfiles/20150120/20150120084529320.png" alt = "\">
Subject. java
package sample;import java.util.List;public interface Subject {public void addObserver(Observer observer);public void removeObserver(Observer observer);public void notifyObservers(List
 
   files);}
 
FileSystem. java
package sample;import java.util.LinkedList;import java.util.List;public class FileSystem implements Subject {private List
 
   files = new LinkedList
  
   ();private List
   
     observers = new LinkedList
    
     ();@Overridepublic void addObserver(Observer observer) {this.observers.add(observer);}@Overridepublic void removeObserver(Observer observer) {this.observers.remove(observer);}@Overridepublic void notifyObservers(List
     
       files) {for (Observer observer : observers) {observer.update(files);}}public void addFile(String file) {files.add(file);this.notifyObservers(files);}public void delFile(String file) {files.remove(file);this.notifyObservers(files);}}
     
    
   
  
 
Observer. java
package sample;import java.util.List;public interface Observer {public void update(List
 
   files);}
 
FileBrowser. java
package sample;import java.util.List;public class FileBrowser implements Observer {@Overridepublic void update(List
 
   files) {this.display(files);}private void display(List
  
    files) {for (String file : files) {System.out.print(file);System.out.print("\t\t");}}}
  
 
Check the results through the client program,
Package sample; public class App {public static void main (String [] args) {Observer window = new FileBrowser (); FileSystem fileSystem = new FileSystem (); fileSystem. addObserver (window); fileSystem. addFile ("file1"); System. out. println ("\ n ===========\ n"); fileSystem. addFile ("file2"); System. out. println ("\ n ===========\ n"); fileSystem. addFile ("file3"); System. out. println ("\ n ===========\ n"); fileSystem. delFile ("file1 ");}} // The output result is as follows: file1 =========== file1file2 =========== file1file2file3 =========== file2file3
In this example, there is only one observer, but in the operating system, we can open multiple folder windows at the same time to view the same directory in different ways. For the above example, we only need to add different FileBrowser classes (implementing the Observer Interface), and do not need to make any modifications to the file system (subject. What problems does the observer mode solve? To answer this question, let's look at what will happen if there is no observer mode? When the internal status of a topic object changes, it must be displayed to notify each viewer, so that the topic object is dependent on each observer, The observer changes this one-to-many dependency into one-to-one dependency. The topic object only depends on the observer object interface and does not depend on the specific implementation, this greatly reduces system coupling and provides flexible support for future reuse and expansion. On the other hand, theme objects only need to focus on their own business, instead of having to care about how the observers update themselves, which is more in line with the Single Responsibility Principle of the class.

What are the parts designed by the observer in JDK?

I believe that everyone has been familiar with awt packages and swing packages when learning java, such as buttons, jbuttons, and JCheckBox classes, such as addActionListener (ActionListener l) and addChangeListener (ChangeListener l) addItemListener (ItemListener l) and other methods. To call these methods to add and register an event listener is to add an observer in the Observer mode, where the listener is the observer. In addition, JDK provides the observer mode for our convenience. the Observable class and Observer interface under the util package can be viewed by yourself. After understanding the Observer mode, you can easily understand the usage of the two classes. In my opinion, the only drawback is that the topic (Observable) is a class rather than an interface, which limits our use.

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.