Event.java 924 B

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