ConstantDispatcher.java

/***************************************************************************
   Copyright 2012 Emily Estes

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
***************************************************************************/
package net.metanotion.util;


import net.metanotion.functor.Thunk;

/** This dispatcher always returns the same message(provided to it's constructor) regardless of the data.
	@param <D> The type of data this dispatcher "operates" on(actually, it completely ignores the data.
	@param <I> The receiver type of the messages generated by the thunk wrapped by this dispatcher.
*/
public final class ConstantDispatcher<I,D> implements Dispatcher<I,D> {
	private static final class T<I> implements Thunk<Message<I>> {
		private final Message<I> m;
		public T(Message<I> m) { this.m = m; }
		@Override public Message<I> eval() { return m; }
	}

	private final Thunk<Message<I>> t;

	/** This constructor will use a null value for the message to return. */
	public ConstantDispatcher() { this(new T<I>(null)); }

	/** This constructor provides a constant value for the message to return.
		@param m The message that will be returned by .dispatch()
	*/
	public ConstantDispatcher(final Message<I> m) { this(new T<>(m)); }

	/** This constructor allows a Thunk to be provided which produces a value for
		the message object, independently of the data. While this message may not
		be "constant" it is "independent" of the data.
		@param t The thunk to provide the message for .dispatch()
	*/
	public ConstantDispatcher(final Thunk<Message<I>> t) { this.t = t;}
	@Override public Message<I> dispatch(final D data) {
		try {
			return t.eval();
		} catch (final Exception e) { throw new RuntimeException(e); }
	}
}