用Java创建自定义事件

时间:2011-06-07 18:48:54

标签: java events listener handler

我想在Java中做这样的事情,但我不知道如何:

当事件“对象1说'你好''发生时, 然后,对象2通过说“你好”来响应该事件。

有人可以给我一个提示或示例代码吗?

5 个答案:

答案 0 :(得分:392)

您可能想要查看observer pattern

以下是一些启动自己的示例代码:

import java.util.*;

// An interface to be implemented by everyone interested in "Hello" events
interface HelloListener {
    void someoneSaidHello();
}

// Someone who says "Hello"
class Initiater {
    private List<HelloListener> listeners = new ArrayList<HelloListener>();

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

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

        // Notify everybody that may be interested.
        for (HelloListener hl : listeners)
            hl.someoneSaidHello();
    }
}

// Someone interested in "Hello" events
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);

        initiater.sayHello();  // Prints "Hello!!!" and "Hello there..."
    }
}

相关文章:Java: Creating a custom event

答案 1 :(得分:27)

您想要的是observer pattern的实现。您可以完全自己完成,也可以使用java.util.Observerjava.util.Observable

等java类

答案 2 :(得分:21)

您可以通过3种不同的方式进行设置:

    Thrower
  1. CatcherCatcher
  2. Thrower 此示例中的另一个类中的
  3. ThrowerCatcher Test
  4. THE WORKING GITHUB EXAMPLE I AM CITING 默认为选项3,尝试其他人只需取消注释您想要成为主要类的“Optional”代码块,并将该类设置为${Main-Class}文件中的build.xml变量:

    投掷旁边代码需要4件事

    import java.util.*;//import of java.util.event
    
    //Declaration of the event's interface type, OR import of the interface,
    //OR declared somewhere else in the package
    interface ThrowListener {
        public void Catch();
    }
    /*_____________________________________________________________*/class Thrower {
    //list of catchers & corresponding function to add/remove them in the list
        List<ThrowListener> listeners = new ArrayList<ThrowListener>();
        public void addThrowListener(ThrowListener toAdd){ listeners.add(toAdd); }
        //Set of functions that Throw Events.
            public void Throw(){ for (ThrowListener hl : listeners) hl.Catch();
                System.out.println("Something thrown");
            }
    ////Optional: 2 things to send events to a class that is a member of the current class
    . . . go to github link to see this code . . .
    }
    

    类文件中需要接收来自类

    的事件的2件事
    /*_______________________________________________________________*/class Catcher
    implements ThrowListener {//implement added to class
    //Set of @Override functions that Catch Events
        @Override public void Catch() {
            System.out.println("I caught something!!");
        }
    ////Optional: 2 things to receive events from a class that is a member of the current class
    . . . go to github link to see this code . . .
    }
    

答案 3 :(得分:1)

以下内容并不完全相同,但相似,我正在寻找一个添加接口方法调用的代码段,但是发现了这个问题,所以我决定为那些像我这样搜索它的人添加此代码段这个问题:

 public class MyClass
 {
        //... class code goes here

        public interface DataLoadFinishedListener {
            public void onDataLoadFinishedListener(int data_type);
        }

        private DataLoadFinishedListener m_lDataLoadFinished;

        public void setDataLoadFinishedListener(DataLoadFinishedListener dlf){
            this.m_lDataLoadFinished = dlf;
        }



        private void someOtherMethodOfMyClass()
        {
            m_lDataLoadFinished.onDataLoadFinishedListener(1);
        }    
    }

用法如下:

myClassObj.setDataLoadFinishedListener(new MyClass.DataLoadFinishedListener() {
            @Override
            public void onDataLoadFinishedListener(int data_type) {
                }
            });

答案 4 :(得分:0)

术语

  • 听众是观察者/处理者
  • dispatcher 是主体/观察者容器

通常,当人们实现 observer pattern 时,他们需要 dispatcher 存在,然后任何 listener 才能订阅它。但是有一种更好的方法叫做 Signals

信号 是一个事件库。它通过引入一个同时允许注册侦听器和调度事件的 Signal 对象来解耦调度器的侦听器。信号是通过代理从接口自动创建的。它负责管理侦听器的所有样板代码,此外还添加了一些不错的代码 API。

Listener -> Signal <- Dispatcher

interface Chat{
    void onNewMessage(String s);    
}

class Foo{
    Signal<Chat> chatSignal = Signals.signal(Chat.class);
    
    void bar(){
        chatSignal.addListener( s-> Log.d("chat", s) ); // logs all the messaged to Logcat
    }
}

class Foo2{
    Signal<Chat> chatSignal = Signals.signal(Chat.class);
    
    void bar2(){
        chatSignal.dispatcher.onNewMessage("Hello from Foo2"); // dispatches "Hello from Foo2" message to all the listeners
    }
}

在本例中,信号是从 Chat 界面自动创建的。它允许 Foo 注册它并允许 Foo2 在没有交互的情况下发送新消息。

免责声明:我是 Signals 的作者。