View Javadoc

1   package cz.cuni.amis.pogamut.base.communication.worldview.react;
2   
3   import cz.cuni.amis.pogamut.base.communication.worldview.IWorldView;
4   import cz.cuni.amis.pogamut.base.communication.worldview.event.IWorldEvent;
5   import cz.cuni.amis.pogamut.base.communication.worldview.event.IWorldEventListener;
6   
7   /**
8    * This abstract class allows you to easily hook a specific event-handling behavior. It automatically
9    * register a listener for a specified {@link IWorldEvent} for you and calls {@link EventReact#react(IWorldEvent)}
10   * method automatically.
11   * <p><p>
12   * If you need to react only once to the event, use {@link EventReactOnce}.
13   * <p><p>
14   * Use {@link EventReact#enable()} and {@link EventReact#disable()} to enable react / disable react. The reaction is enabled
15   * as default.
16   * <p><p>
17   * <b>WARNING:</b>Use as anonymous class, but <b>save it as a field</b> of your class! Note, that we're using weak-references to 
18   * listeners and if you do not save pointer to the object, it will be gc()ed!
19   * 
20   * @author Jimmy
21   *
22   * @param <EVENT>
23   */
24  public abstract class EventReact<EVENT extends IWorldEvent> {
25  
26  	protected IWorldEventListener<EVENT> reactListener = new IWorldEventListener<EVENT>() {
27  
28  		@Override
29  		public void notify(EVENT event) {
30  			preReact(event);
31  			react(event);
32  			postReact(event);
33  		}
34  	
35  	};
36  	
37  	protected IWorldView reactWorldView;
38  
39  	protected Class<EVENT> reactEventClass;
40  	
41  	private boolean reactHooked = false;
42  	
43  	public EventReact(Class<EVENT> eventClass, IWorldView worldView) {
44  		this.reactWorldView = worldView;
45  		this.reactEventClass = eventClass;
46  		enable();
47  	}
48  	
49  	/**
50  	 * Disables the reaction.
51  	 */
52  	public synchronized void disable() {
53  		if (reactHooked) {
54  			reactHooked = false;
55  			reactWorldView.removeEventListener(reactEventClass, reactListener);
56  		}
57  	}
58  	
59  	/**
60  	 * Enables the reaction.
61  	 */
62  	public synchronized void enable() {
63  		if (!reactHooked) {
64  			reactHooked = true;
65  			if (!reactWorldView.isListening(reactListener)) reactWorldView.addEventListener(reactEventClass, reactListener);
66  		}
67  	}
68  	
69  	/**
70  	 * pre-{@link EventReact#react(IWorldEvent)} hook allowing you to do additional work before the react method.
71  	 * @param event
72  	 */
73  	protected void preReact(EVENT event) {
74  	}
75  
76  	/**
77  	 * React upon event notification.
78  	 * @param event
79  	 */
80  	protected abstract void react(EVENT event);
81  	
82  	/**
83  	 * post-{@link EventReact#react(IWorldEvent)} hook allowing you to do additional work after the react method.
84  	 * @param event
85  	 */
86  	protected void postReact(EVENT event) {
87  	}
88  
89  }