Simple java message dispatching system

前端 未结 3 1850
清歌不尽
清歌不尽 2021-01-29 20:35

I\'m working on a little Java game in which all sorts of events can happen. There are at least a couple of dozen basic events that various event handlers may be interested in.

3条回答
  •  闹比i
    闹比i (楼主)
    2021-01-29 20:49

    Java beans should have had this interface: it makes life simpler.

    interface PropertyChangeProvider {
      void addPropertyChangeListener(PropertyChangeListener l);
      void addPropertyChangeListener(String property, PropertyChangeListener l);
      void removePropertyChangeListener(PropertyChangeListener l);
      void removePropertyChangeListener(String property, PropertyChangeListener l);
    }
    

    Implement it all over the place.

    Make a blackboard class (probably a singleton. this is a sketch only)

    public class Blackboard implements PropertyChangeListener,PropertyChangeProvider {
    
    static Blackboard getInstance(){
        // implement this
    }
    
    void initialise(){
       // start the thread here
    }
    
    void republish(){
         // this can save you heartache too.
    }
    
    
    }
    

    Give Blackboard a thread, listen for events and republish using its own thread.

    Classes can just publish their events to the blackboard.

    Subscribe to the blackboard for events.

    If you want you can persist events, allow republishing etc.

    For something inside an app it is very good. (works just as well as a data interchange interface as well!)

提交回复
热议问题