Alternate of C# Events in Java

后端 未结 4 1822
迷失自我
迷失自我 2020-12-24 02:55

I am .Net developer. i want to know that is there any event handling mechanism in Java for Events Handling like C#.

what i want to do is i want to raise/fire an even

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 03:48

    Although most of the examples will be to do with GUI events, the principles are basically the same. You basically want an interface or abstract class to represent a handler for the event, e.g.

    public interface EventHandler
    {
        // Change signature as appropriate of course
        void handleEvent(Object sender, EventArgs e);
    }
    

    then the publisher of the event would have:

    public void addEventHandler(EventHandler handler)
    public void removeEventHandler(EventHandler handler)
    

    It would either keep a list of event handlers itself, or possibly have them encapsulated in a reusable type. Then when the event occurs, you just call handleEvent in each handler in turn.

    You can think of delegate types in C# as being very similar to single-method interfaces in Java, and events are really just an add/remove pair of methods.

提交回复
热议问题