zoukankan      html  css  js  c++  java
  • JAVA : 简单event机制的实现(伪码)

    <S> 
    public interface EventBase<S> {
    void onEvent(S source, Object[]... arguments);
    }
    <S,T extends EventBase<S>>
    public class EventSender<S, T> {
    private List<T> receivers = new ArrayList<T>();
    public void addReceiver(T receiver) {
    if (null == receiver) 
    throw new RuntimeException("Can't add null as receiver");
    this.receivers.add(T);
    }
    public void removeReceiver(T receiver) {
    if(this.receivers.contains(receiver)) {
    this.receivers.remove(receiver);
    }
    }
    public void triggerEvent(S source, Object[]... arguments) {
    for(T receiver : this.receivers) {
    receiver.onEvent(source, arguments);
    }
    }
    }
    //declare the event 
    <S>
    public interface OnLoadEvent<S> extends EventBase<S {
    }
    //test class
    public MyEntityObj {
    //use the event in the class
    public EventSender<MyEntityObj, OnLoadEvent<MyEntityObj>> onLoad() {
    return onLoadEvent;
    }
    private EventSender<MyEntityObj, OnLoadEvent<MyEntityObj>> onLoadEvent = new ....;
    private void someMethod() {
    //do something
    this.onLoad().triggerEvent(this, "This is a test", 100);
    }
    }
    //receiver class
    public class SimpleReceiver {
    MyEntityObj obj;
    class myOnLoadHandler implements OnLoadEvent<SimpleReceiver> {
    void onEvent(S source, Object[]... arguments){
    //print something here when receive the event
    }
    }
    public void init() {
    //register event
    obj.onLoad().addReceiver(new myOnLoadHandler());
    }
    }
  • 相关阅读:
    2017-12 CDQZ集训(已完结)
    BZOJ1492 货币兑换 CDQ分治优化DP
    BZOJ2001 [Hnoi2010]City 城市建设 CDQ分治
    树套树小结
    跑路了
    NOI2020 游记
    半平面交模板
    Luogu 3245 大数
    Luogu 3246 序列
    test20190408(十二省联考)
  • 原文地址:https://www.cnblogs.com/sliencer/p/2410891.html
Copyright © 2011-2022 走看看