关于java:Java中完美实现C的EventHandler事件模式代码优雅解耦合

42次阅读

共计 1815 个字符,预计需要花费 5 分钟才能阅读完成。

hzEvents

A cSharp-like event model for java, decoupe code gracefully.
Java 中完满实现 C# 的 Event-EventHandler-EventArgs 事件模式,代码优雅解耦合。

用法

Import cn.hz.Events.jar in your project first, or import source code.
首先我的项目中引入 cn.hz.Events.jar 包,或源码。

Subject

Class which supply events and fire events.
蕴含事件并触发事件的类。

public class Subject {
    //Simple event
    Event event1 = new Event();
    //Event with arguments
    Event2<String, Integer> eventWithArg = new Event2<>();
    //Sample of removeListener
    Event3<Subject, Integer, Integer> eventRemoved = new Event3<>();
    public void start() {
        // fire events at the appropriate time
        onEvent1(new EventArgs());
        onEvent2(new EventArgs2<>("Event2", 2));
        onEvent3(new EventArgs3<>(this, 3, 3));
    }
    protected void onEvent1(EventArgs e) {if (!event1.isEmpty()) {event1.fire(this, e);
        }
    }
    protected void onEvent2(EventArgs2<String, Integer> e) {if (!eventWithArg.isEmpty()) {eventWithArg.fire(this, e);
        }
    }
    protected void onEvent3(EventArgs3<Subject, Integer, Integer> e) {if (!eventRemoved.isEmpty()) {eventRemoved.fire(this, e);
        }
    }
}

Observer

Class which subscribe events.
事件订阅者(或观察者).

public class Observer {public void bindEvents(Subject subject, EventChain chain) {
        // bind event listeners
        subject.event1.addListener((o, e) -> {System.out.println("event1 fired.");
        });
        subject.eventWithArg.addListener((o, e) -> {System.out.println("eventWithArg fired, args:" + e.getData1() + "," + e.getData2());
        });
        chain.chainEvent.addListener((o, e) -> {System.out.println("chainEvent fired, args:" + e.getData1() + "," + e.getData2());
        });
        EventHandler3<Subject, Integer, Integer> handler3 = this::onEvent3;
        subject.eventRemoved.addListener(handler3);
        //remove event binding. message of event3 will not be shown
        subject.eventRemoved.removeListener(handler3); //Target must be exactly the same as addListener() !}
    private void onEvent3(Object o, EventArgs3<Subject, Integer, Integer> e) {System.out.println("event3 fired, args:" + e.getData1() + "," + e.getData2() + "," + e.getData3());
    }
}

详见源码(Source code):https://github.com/hzsrc/hzEv…

正文完
 0