Implementing event delegation patterns in the Java language

Source: Internet
Author: User
Tags object object

Event-Delegate mode is a more common design pattern, but the Java language itself does not encapsulate it in a certain way, so it is difficult to implement (it is easy to understand the rationale), by contrast. NET is much easier.

As a Java enthusiasts, how to bow to such a small difficulty, but the internet search, but did not find the relevant solutions, have to do a package.

In fact, the combination of examples is better, then I use a small example to draw out this design pattern.

A class, there are two types of students, Class A: Do not learn, play, but play something different, some do games, and is watching TV (a bit unreasonable)

Class B: Sentinel students, special look at the teacher's movement, if the teacher into the class immediately notify everyone.

So the formation of a demand, sentinel students to inform all playing students: The teacher came, and different students have different responses, some immediately turn off the TV, some stop playing games.

Design requirements are as follows, so that a class of students and B-class students fully decoupled, that is, Class A completely do not know Class B students, but can inform Class B students.

The code and description are as follows:

event class, which defines a class of events:

Package lnurd.test;   
Import Java.lang.reflect.Method;   

Import Java.util.Date;   
    public class Event {//object to execute method private object;   
    The method name to execute private String methodname;   
    The parameter to execute method private object[] params;   

    The parameter type to execute the method private class[] paramtypes; Public event () {} public event (Object object,string Methodname,object...args) {THIS.OBJECT=OBJEC   
        T   
        This.methodname=methodname;   
        This.params=args;   
    Contractparamtypes (This.params); An array of parameter types is generated from the parameter array private void Contractparamtypes (object[] params) {this.paramtypes=new Class[pa   
        Rams.length];   
        for (int i=0;i<params.length;i++) {this.paramtypes[i]=params[i].getclass ();   
    } public Object GetObject () {return object;   
}//Several setter getter omit public void Setparamtypes (class[] paramtypes) {        This.paramtypes = Paramtypes; //Executes the method of this object public void Invoke () throws exception{methods Method=object.getclass (). GetMethod (t   
        His.getmethodname (), this.getparamtypes ());   
        if (Null==method) {return;   
    } method.invoke (This.getobject (), This.getparams ());   }   
}

EventHandler class, the carrier of several event classes, provides a way to execute all event

Package lnurd.test;   

Import java.util.ArrayList;   
Import java.util.List;   

public class EventHandler {   
    //Is list<event> objects with a List   
    private;   

    Public EventHandler () {   
        objects=new arraylist<event> ();   
    }   
    Add an event to be executed by an object, and the required arguments public   
    void Addevent (Object object,string methodname,object...args) {   
        Objects.add ( New Event (Object,methodname,args));   
    }   
    Notifies all objects to perform the specified event public   
    void Notifyx () throws exception{for   
        (event e:objects) {   
            e.invoke ();   
        }   
    }   
}  

Lookout Student: Here we abstract an abstract class, because the sentry has the duty and the careless,

But they have functional methods of 1. Increase the number of students who need help sentry 2. Inform all students who need to be lookout: The teacher is here.

Package lnurd.test;   

Public abstract class Notifier {   
    private EventHandler eventhandler=new EventHandler ();   

    Public EventHandler Geteventhandler () {return   
        EventHandler;   
    }   
    public void setEventHandler (EventHandler EventHandler) {   
        this.eventhandler = EventHandler;   
    }   
    Increase the number of students who need help to watch the public   
    abstract void AddListener (Object object,string Methodname,object...args);   
    Tell all the students to help watch out: The teacher came. Public   
    abstract void Notifyx ();   
}  

Then came the sentry's concrete implementation, which only implemented two

1 Conscientious Sentry Goodnotifier.

2 Sloppy Sentry Badnotifier.

Package lnurd.test;   

The public class Goodnotifier extends Notifier {   

    @Override  
    the public void AddListener (object, String methodname, Object ... args) {   
        System.out.println ("There is a new classmate entrusted to dutifully sentry!");   
        This.geteventhandler (). Addevent (object, methodname, args);   

    @Override public  
    void Notifyx () {   
        System.out.println ("The conscientious sentry told all the students who needed help: the teacher came");   
        try{   
            This.geteventhandler (). Notifyx ();   
        } catch (Exception e) {   
            e.printstacktrace ();   

}}} Similar to Badnotifier code, no longer repeat.  

Next is the student playing the game: Playinggamelistener

Package lnurd.test;   

Import java.util.Date;   

public class Playinggamelistener {public   
    Playinggamelistener () {   
        System.out.println ("I am playing the game start Time" +new Date () );   
    }   
    public void Stopplayinggame (date date) {   
        System.out.println ("The teacher is coming, come back to the seat, end Time" +date);   
    }   
  

In the next is the TV-watching student Watchingtvlistener

Package lnurd.test;   

Import java.util.Date;   

public class Watchingtvlistener {public   
    Watchingtvlistener () {   
        System.out.println ("I am watching TV" +new Date);   
    } Public   
    void Stopwatchingtv (date date) {   
        System.out.println ("The teacher is here, close the TV soon.") End Time "+date");   
    }   
  

Test code:

Create a dutiful Sentry   
Notifier goodnotifier=new goodnotifier ();   

Create a game to play the classmate, began to play the game   
Playinggamelistener playinggamelistener=new Playinggamelistener ();   
To create a TV-watching classmate, began to watch TV   
Watchingtvlistener watchingtvlistener=new watchingtvlistener ();   
Students playing the game told Sentinel students, the teacher came to tell the   
Goodnotifier.addlistener (Playinggamelistener, "Stopplayinggame", New Date ());   
Watching TV students told Sentinel students, the teacher came to tell the   
Goodnotifier.addlistener (Watchingtvlistener, "Stopwatchingtv", New Date ());   
try{   
    //A little time after   
    Thread.Sleep (1000);   
} catch (Exception e) {   
    e.printstacktrace ();   
}   
The teacher appeared, Sentinel people to inform all the students to help: The teacher came to the   
Goodnotifier.notifyx ();  

Comments:

1. The sentry is completely decoupled from the existence of the player. (Of course, credit is due to event and EventHandler, and these two classes are generic)

2. When the teacher comes, the player stops the game and returns to his seat, watching TV and turning off the TV. (one notification, different methods of different classes executed)

3. The expansion is very high, another play basketball students to write a basketball student class, and in the test code to tell the Sentinel, just fine, the sentry has not changed. Good reusability

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.