Action.java 1018 B

123456789101112131415161718192021222324252627282930313233343536
  1. package holeg.utility.events;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. import java.util.function.Consumer;
  5. /**
  6. * An Action is a parametrized event. Classes can assign functions to this action. When the event should occur it can be broadcast to all listener.
  7. * @param <T>
  8. */
  9. public class Action<T> {
  10. /**
  11. * Holds all lambdas that will trigger when the event is broadcast.
  12. */
  13. private final Set<Consumer<T>> listeners = new HashSet<Consumer<T>>();
  14. /**
  15. * Adds an event listener. Normally a lambda function.
  16. * @param listener the action that is triggered
  17. */
  18. public void addListener(Consumer<T> listener) {
  19. listeners.add(listener);
  20. }
  21. /**
  22. * Broadcast the action.
  23. */
  24. public void removeListener(Consumer<T> listener) {
  25. listeners.remove(listener);
  26. }
  27. /**
  28. * Removes an event listener.
  29. * @param listener the action that is triggered
  30. */
  31. public void broadcast(T listener) {
  32. listeners.forEach(x -> x.accept(listener));
  33. }
  34. }