View Javadoc

1   package cz.cuni.amis.utils.flag;
2   
3   import cz.cuni.amis.utils.listener.Listeners;
4   
5   /**
6    * Listener for {@link ReasonFlag}. It allows to sense reasons of the changes. It provides
7    * a simple message passing mechanism along with changes in the flag.
8    * <p><p>
9    * For instance, it allows us to send reason why the Mediator has been shut down. 
10   * 
11   * @author Jimmy
12   *
13   * @param <TYPE>
14   * @param <REASON>
15   */
16  public interface ReasonFlagListener<TYPE, REASON> extends FlagListener<TYPE> {
17  	
18  	/**
19  	 * Notifier for the ReasonFlagListener.
20  	 * 
21  	 * @author Jimmy
22  	 *
23  	 * @param <T>
24  	 */
25  	public static class ReasonFlagListenerNotifier<T, R> extends FlagListener.FlagListenerNotifier<T> {
26  		
27  		private R reason;
28  		
29  		public ReasonFlagListenerNotifier() {
30  			super();
31  		}
32  		
33  		public ReasonFlagListenerNotifier(T changedValue) {
34  			super(changedValue);
35  		}
36  		
37  		public ReasonFlagListenerNotifier(T changedValue, R reasonForChange) {
38  			super(changedValue);
39  			this.reason = reasonForChange;
40  		}
41  		
42  		public void setReason(R reason) {
43  			this.reason = reason;
44  		}
45  		
46  		/**
47  		 * If ReasonFlagListener is passed into the method, it is redirected into appropriate method.
48  		 */
49  		@Override
50  		public void notify(FlagListener<T> listener) {
51  			if (listener instanceof ReasonFlagListener) {
52  				notify((ReasonFlagListener)listener);
53  			} else {
54  				super.notify(listener);
55  			}
56  		}
57  
58  		public void notify(ReasonFlagListener<T, R> listener) {
59  			if (reason == null) {
60  				// if there is no reason specified, call simple flagChanged
61  				listener.flagChanged(value);
62  			} else {
63  				// if the reason is specified, call appropriate method
64  				listener.flagChanged(value, reason);
65  			}
66  		}
67  		
68  	}
69  
70  	/**
71  	 * Adapter for the simple FlagListener that does not care about reasons (the reason is masked
72  	 * during the call...)
73  	 * 
74  	 * @author Jimmy
75  	 *
76  	 * @param <T>
77  	 * @param <R>
78  	 */
79  	public static class FlagListenerAdapter<T, R> implements ReasonFlagListener<T, R> {
80  		
81  		private FlagListener<T> listener;
82  
83  		public FlagListenerAdapter(FlagListener<T> listener) {
84  			this.listener = listener;
85  		}
86  
87  		@Override
88  		public void flagChanged(T changedValue, R reason) {
89  			listener.flagChanged(changedValue);			
90  		}
91  
92  		@Override
93  		public void flagChanged(T changedValue) {
94  			listener.flagChanged(changedValue);
95  		}
96  		
97  	}
98  
99  	/**
100 	 * This method is called whenever the flag has changed its value and the changer
101 	 * also specified a reason for this change.
102 	 * @param changedValue
103 	 * @param reason
104 	 */
105 	public void flagChanged(TYPE changedValue, REASON reason);
106 	
107 }