Home > Java > javaTutorial > How Can I Create and Handle Custom Events in Java Using the Observer Pattern?

How Can I Create and Handle Custom Events in Java Using the Observer Pattern?

Linda Hamilton
Release: 2024-12-04 02:38:10
Original
898 people have browsed it

How Can I Create and Handle Custom Events in Java Using the Observer Pattern?

Creating Custom Events in Java

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..."
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template