All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.requirementsascode.SystemReaction Maven / Gradle / Ivy

There is a newer version: 2.0
Show newest version
package org.requirementsascode;

import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * An instance of this class represents a system reaction as a function, even if it has been specified as
 * a Consumer or Runnable by the user of the library. This approach simplifies development of the rest of the API.
 * 
 * An instance of this class also allows access to the original object (i.e. Consumer, Runnable, or Function)
 * specified via .system(..) or .systemPublish() by the user of the library.
 * That element is called modelObject.
 * 
 * @author b_muth
 *
 * @param  the kind of message that is the input for this system reactions
 */
public class SystemReaction implements Function {
	private Object modelObject;
	private Function internalFunction;

	SystemReaction(Consumer modelObject) {
		this.modelObject = Objects.requireNonNull(modelObject);
		
		Function nonPublishingReaction = message -> {
			modelObject.accept(message);
			return null;
		};
		this.internalFunction = nonPublishingReaction;
	}

	SystemReaction(Runnable modelObject) {
		this((Consumer) ignoredRunner -> modelObject.run());
		this.modelObject = modelObject;
	}

	SystemReaction(Supplier modelObject) {
		this.modelObject = Objects.requireNonNull(modelObject);
		
		Function publishingReaction = (Function) message -> modelObject.get();
		this.internalFunction = publishingReaction;
	}

	SystemReaction(Function modelObject) {
		Objects.requireNonNull(modelObject);
		this.modelObject = modelObject;
		this.internalFunction = modelObject;
	}

	public Object getModelObject() {
		return modelObject; 
	}

	@Override
	public Object apply(T message) {
		return internalFunction.apply(message);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy