Observer mode (listener mode)

Observer Pattern Basic Concepts

 

       Observer mode (Observer) , also known as publish/subscribe mode;

       The Observer pattern is one of the software design patterns. In this pattern, a target (observed) manages all the observers that depend on it, and is actively notified when its own state changes. This is usually accomplished by invoking methods provided by each observer.

       The Observer pattern perfectly separates the observer from the observed object.

       A principle of object-oriented design is that each class in the system will focus on one function, not the other. An object does only one thing and does it well. The Observer pattern draws clear boundaries between modules, improving the maintainability and reusability of the system.

 

Implementation of the Observer Pattern

 

       The Observer pattern can be implemented in many ways, but fundamentally, the pattern must contain two roles: the observer and the observed object. There is a logical relationship of "observation" between the observer and the observed. When the observed changes, the observer will observe such changes and respond accordingly.

       When implementing the observer pattern, it should be noted that the interaction between the observer and the observed object cannot be embodied as a direct call between classes, otherwise the observer and the observed object will be tightly coupled, fundamentally Violates the principles of object-oriented design. Whether the observer "observes" the observed object, or the observed "notifies" the observer of its own changes, it should not be called directly.

       There are many forms to implement the observer pattern. One of the more intuitive ones is to use a form of "registration - notification - deregistration". Such a process is described in detail below:

 

     1. The observer

 

  (Observer) registers itself with the observed object (Subject), and the observed object stores the observer in a container (Container).

 

     2. The object to be observed

 

  When the observed object changes, get all the registered observers from the container, and notify the observers of the changes.

 

      3. Cancellation of observation

 

  The observer tells the subject to revoke the observation, and the subject removes the observer from the container.

 

       When the observer registers itself in the observer's container, the observer should not interrogate the specific type of the observer, but should use the interface of the observer . The advantage of this is that assuming that there are other observers in the program, as long as this observer is also the same interface implementation.

 

 

Listeners and Listener Patterns

 

      The listener is an implementation of the observer pattern, and the listener pattern is also a type of the observer pattern.

       Listener mode is the monitoring of some common operation. This operation is handled accordingly when this operation is executed.

Included elements:

                          1. The event to be monitored defines the Event

                          2. Listener to monitor the event

                          3. The event action to be monitored

                          4. Monitor

       Element's Responsibilities:

                          1. Define the event type definition of the event to be monitored, and other special definitions related to the event

                          2. Listener, used to define the interface to perform the operation after the event occurs

                          3. The events and operations to be monitored, for the events to be monitored, he must include the registration function of the monitored events

                          4. The monitor must implement the event interface to be monitored, and complete the operation content after the time occurs.

       Here is an example to illustrate the general implementation of the listening mode:

 

       1. First of all, you need to define the event, which types of events the listener handles, that is, what kind of event is used to trigger the listener. There are many types of events. Here you can define an event interface to abstract all event types.

 

 

Java code   收藏代码
  1. /** 
  2.  * Event interface, in which three types of events are defined, create, delete, update 
  3.  */  
  4. public  interface  MyEvent {  
  5.       
  6.     public static final String createEvent = "CREATE_EVENT";  
  7.     public static final String deleteEvent = "DELETE_EVENT";  
  8.     public static final String updateEvent = "UPDATE_EVENT";  
  9.   
  10.     public String getEvent();  
  11.       
  12. }  

 

 

2、给出一个监听器的接口

 

 

Java代码   收藏代码
  1. /** 
  2.  * 定义监听器,该监听器只监听MyEvent类型的事件 
  3.  */  
  4. public interface MyListener {  
  5.     public void handle(MyEvent myEvent);  
  6. }  

 

 

3、监听器的实现,该实现根据事件类型的不同做不同的处理

 

 

Java代码   收藏代码
  1. public class MyListenerImpl implements MyListener {  
  2.     public void handle(MyEvent myEvent) {  
  3.         if(myEvent.getEvent().equals("CREATE_EVENT")){  
  4.             System.out.println("myListener get a create event!");  
  5.         }  
  6.         else if(myEvent.getEvent().equals("DELETE_EVENT")){  
  7.              ...   
  8.         }  
  9.          ...   
  10.     }  
  11. }  

 

 

4、有了监听器的实现,肯定需要一个事件的实现,不过事件的实现类可以是专指某个类型的pojo,也可以是一个事件类型在使用时被设置的类,下面的实现是第一种,直接定义了一个create事件的实现类。

 

 

Java代码   收藏代码
  1. public class MyCreateEventImpl implements MyEvent {  
  2.     private String type="";  
  3.     public MyCreateEventImpl(){  
  4.         this.type = MyEvent.createEvent;  
  5.     }  
  6.     public String getEvent() {  
  7.         return this.type;  
  8.     }  
  9. }  

 

 

5、基础工作都做好后,就可以在想添加监听的类中实施监听功能了。

 

 

Java代码   收藏代码
  1. public class MyCreateAction {  
  2.     //引入监听器  
  3.     private MyListener myListener;  
  4.     //引入事件,用来传给Listener进行处理  
  5.     private static MyEvent myEvent;  
  6.     public void setListener(MyListener myListener){  
  7.         this.myListener = myListener;  
  8.     }  
  9.     private void handleListener(MyEvent myEvent){  
  10.         //触发监听  
  11.         this.myListener.handle(myEvent);  
  12.     }  
  13.     public void execute(){  
  14.         //设置事件的类型为create  
  15.         myEvent = new MyCreateEventImpl();  
  16.         System.out.println("create start!");  
  17.         this.handleListener(myEvent);  
  18.         System.out.println("create end!");  
  19.     }  
  20.   
  21.     //调用被监听的类,测试监听效果  
  22.     public static void main(String[] args) {  
  23.         MyCreateAction action = new MyCreateAction();  
  24.         MyListenerImpl myListener = new MyListenerImpl();  
  25.         //设置监听器的实现  
  26.         action.setListener(myListener);  
  27.         action.execute();  
  28.     }  
  29. }  

 

 

输出的结果为:

 

create start!

myListener get a create event!

create end!

 

至此,监听器模式的基本工作原理就已经十分清楚了。

有些东西听起来很深奥,只要花时间看一下,再动手实验一把,马上就豁然开朗了~

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326475492&siteId=291194637