Observer mode and event-driven mode instance comparison _ design pattern

Source: Internet
Author: User
Tags event listener

The actors involved in the Observer pattern are:

Abstract theme (Subject) role: Abstract theme Roles Keep all references to observer objects in a cluster (such as a ArrayList object), each subject can have any number of observers. Abstract topics provide an interface for adding and removing observer objects, and abstract theme roles are also called abstract-observer (observable) roles.

Specific theme (ConcreteSubject) role: The state is deposited in a specific observer object, and all registered observers are notified when the internal state of the specific subject changes. The specific theme role is also called the specific Observer (concrete observable) role.

Abstract observer (OBSERVER) role: Defines an interface for all specific observers and updates itself when a topic is notified, an interface called an update interface.

The specific observer (CONCRETEOBSERVER) role: The State of the store and the topic itself. The specific observer role implements the update interface required by the abstract observer role to coordinate itself with the state of the subject.   The specific observer role can maintain a reference to a specific subject object, if necessary. Source

Abstract Theme Role Classes

Public abstract class Subject {
    /**
     * To hold the registered observer object *
     *
    private    list<observer> List = new Arraylist<observer> ();
    /**
     * Registered Observer Object
     * @param observer Observer Object * * Public
    VOID Attach (Observer observer) {
        
        List.add ( observer);
        System.out.println ("attached an observer");
    }
    /**
     * Delete Observer object
     * @param observer Observer Object * * Public
    VOID Detach (Observer observer) {
        
        LIST.REMOVE (Observer);
    }
    /**
     * Notifies all registered Observer objects */
     public
    void Nodifyobservers (String newstate) {for
        
        (Observer observer:list) {
            observer.update (newstate);}}}

Specific Theme Role Classes

public class ConcreteSubject extends subject{
    
    private String state;
    
    Public String GetState () {return state
        ;
    }

    public void Change (String newstate) {state
        = newstate;
        System.out.println ("The theme is:" + state);
        States change, notifying each observer
        This.nodifyobservers (state);
    }

Abstract Observer Role Class

Public interface Observer {
    /**
     * Update interface
     * @param    State Update Status *
    /public void update (String State);
}

Specific observer Role class

public class Concreteobserver implements Observer {
    //Observer's state
    private String observerstate;
    
    @Override public
    void Update (String state) {
        /**
         * Updates The observer's status so that it is consistent with the state of the target * *
        observerstate = State;
        System.out.println ("Status:" +observerstate);
    }

Client class

public class Client {public

    static void Main (string[] args) {
        //Create Subject Object
        concretesubject subject = new concrete Subject ();
        Create the Observer object
        Observer Observer = new Concreteobserver ();
        Registers the Observer object on the Subject Object
        Subject.attach (Observer);
        Change the status of the Subject Object
        subject.change ("New State");
    }

The results of the operation are as follows

At run time, the client first creates an instance of the specific subject class, as well as an observer object. It then invokes the attach () method of the Subject object, registering the Observer object with the subject object, that is, adding it to the subject object's aggregation.

At this point, the client invokes the change () method of the theme, changing the internal state of the subject object. The Subject object invokes the Notifyobservers () method of the superclass when the state changes, notifying all registered observer objects.

The Java event mechanism consists of three parts: an event, an event listener, and an event source.

1, the event. Generally inherits from the Java.util.EventObject class, encapsulates the event source object and the information related to the event.

Com.javaedu.event.CusEvent class Java code    package com.javaedu.event;      Import  java.util.EventObject;     /**   *  event class, for encapsulating event sources and some event-related parameters .   *   @author  Eric   */   public class cusevent extends eventobject  {       private static final long serialversionuid  = 1L;       private object source;//Event Source                public cusevent (Object source) {           super (source);            this.source = source;       }           public object getsource ()  {            return source;       }           Public void setsource (object source)  {            this.source = source;       }  }  

2, Event listener. Implement the Java.util.EventListener interface, register on the event source, and get the corresponding listener to call its internal callback method when the property or state of the event source changes.

Com.javaedu.event.CusEventListener class Java code    package com.javaedu.event;      import java.util.eventlistener;     /**   *  event listeners, Implements the Java.util.EventListener interface. Define the callback method, put what you want    *  into this method, because the event source will call this method when the corresponding event occurs.    *  @author  Eric   */   public class cuseventlistener  implements eventlistener {              // The callback method after the event occurred        public void firecusevent (cusevent e) {           EventSourceObjecteObject =  (Eventsourceobject) E.getsource ();           system.out.println ("My name  has been changed! ");            system.out.println ("I got a new  name,named&Nbsp;\ "" +eobject.getname () + "\" ");    }  }  

3, Event source. Where an event occurs, an event occurs because an attribute or state of the event source has changed (for example, the button is clicked, the value of the textbox has changed, and so on). In other words, the corresponding event object is generated. Because event listeners are registered on the event source, the event source class should have a container (list,set, and so on) for the listener.

 com.javaedu.event.eventsourceobject class Java code    package com.javaedu.event;       import java.util.hashset;   import java.util.iterator;   import  java.util.set;     /**   *  Event source .   *  @author  Eric   */   public class eventsourceobject {       private  String name;       //Listener Container        private  Set<CusEventListener> listener;       public  Eventsourceobject () {           this.listener = new  HashSet<CusEventListener> ();           this.name  =  "DefaultName";       }       // Registering listeners    &nbs for event sourcesP;   public void addcuslistener (cuseventlistener cel) {            this.listener.add (CEL);       }       //When an event occurs, notify all listeners registered on the event source to respond appropriately (invoke the callback method)        protected  void notifies () {           CusEventListener  cel = null;           iterator<cuseventlistener > iterator = this.listener.iterator ();            while (Iterator.hasnext ()) {                cel = iterator.next ();                cel.firecusevent (New cusevent (this));            }       }       public string getname ()   {           return name;        }       //simulate event triggers, which trigger events when the value of the member variable name changes.        public void setname (string name)  {            if (!this.name.equals (name)) {                this.name = name;                notifies ();            }             }  }   

Following is the Main method class

 com.javaedu.event.maintest class, Java code    package com.javaedu.event;      public class maintest {          /**        *  @param  args       */        public static void main (String[] args)  {            eventsourceobject object = new eventsourceobject ();           //Registered Listener             object.addcuslistener (New cuseventlistener () {                 @Override                 public void firecusevent (cusevent e)  {                     super.firecusevent (e);                }          &NBSP;&NBSP});           //triggering event             object.setname ("Eric");       }  }  

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.