Create a custom event in Java

Asked 2 years ago, Updated 2 years ago, 99 views

If an object says "hello" in object 2, I want to create an event where I answer "hello" in object 2 I don't know what to do. Is there a simple example source?

java events listener handler

2022-09-22 22:16

1 Answers

I think we're looking for an observer pattern. The concept of the observer pattern is http://warmz.tistory.com/entry/Observer-Pattern-%EC%98%B5%EC%A0%80%EB%B2%84-%ED%8C%A8%ED%84%B4 It's well explained here, so please refer to it.

This is a sample code.

import java.util.*;

interface HelloListener {
    void someoneSaidHello();
}

class Initiater {
    private List<HelloListener> listeners = new ArrayList<HelloListener>();

    public void addListener(HelloListener toAdd) {
        listeners.add(toAdd);
    }

    public void sayHello() {
        System.out.println("Hello!!");

        for (HelloListener hl : listeners)
            hl.someoneSaidHello();
    }
}

class Responder implements HelloListener {
    @Override
    public void someoneSaidHello() {
        System.out.println("Hello there...");
    }
}
class Test {
    public static void main(String[] args) {
        Initiater initiater = new Initiater();
        Responder responder = new Responder();

        initiater.addListener(responder);

        Initiator.sayHello(); // When someone says "Hello!!" other objects answer "Hello there..." 
    }
}


2022-09-22 22:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.