Home >Java >javaTutorial >How Can I Create and Handle Custom Events in Java Using the Observer Pattern?
In Java, it is possible to create custom events to enable different objects to communicate with each other. Consider a scenario where an "object 1" needs to trigger an action when it performs a specific event, such as uttering "hello," and "object 2" responds by acknowledging the event by saying "hello" in return.
To achieve this, you can utilize the observer pattern. Below is an example that demonstrates how to create and handle custom events:
import java.util.*; // Define an interface for event listeners interface HelloListener { void someoneSaidHello(); } // Class that initiates the event (Object 1) class Initiater { private List<HelloListener> listeners = new ArrayList<>(); // Add an event listener public void addListener(HelloListener toAdd) { listeners.add(toAdd); } // Trigger the event public void sayHello() { System.out.println("Hello!!"); // Notify all listeners for (HelloListener hl : listeners) hl.someoneSaidHello(); } } // Class that listens to the event (Object 2) class Responder implements HelloListener { @Override public void someoneSaidHello() { System.out.println("Hello there..."); } } // Main class class Test { public static void main(String[] args) { Initiater initiater = new Initiater(); Responder responder = new Responder(); // Attach a listener to the initiator initiater.addListener(responder); // Trigger the event initiater.sayHello(); // Prints "Hello!!!" and "Hello there..." } }
In this example, the Initiater class fires a "Hello" event, which is handled by the Responder class. When the Initiater says "hello," the Responder responds with "hello there."
The above is the detailed content of How Can I Create and Handle Custom Events in Java Using the Observer Pattern?. For more information, please follow other related articles on the PHP Chinese website!