How to implement callbacks in Java

前端 未结 4 1268
Happy的楠姐
Happy的楠姐 2020-12-13 11:25

I have a class called CommunicationManager which is responsible for communication with server.

It includes methods login() and onLoginResponse()

4条回答
  •  醉梦人生
    2020-12-13 11:54

    The idiom used in Java to achieve callback behaviour is Listeners. Construct an interface with methods for the events you want, have a mechanism for registering listener object with the source of the events. When an event occurs, call the corresponding method on each registered listener. This is a common pattern for AWT and Swing events; for a randomly chosen example see FocusListener and the corresponding FocusEvent object.

    Note that all the events in Java AWT and Swing inherit ultimately from EventObject, and the convention is to call the listener SomethingListener and the event SomethingEvent. Although you can get away with naming your code whatever you like, it's easier to maintain code which sticks with the conventions of the platform.

提交回复
热议问题