`
xylong
  • 浏览: 191349 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

我说guava之EventBus

 
阅读更多

guava(http://code.google.com/p/guava-libraries/),对于使用apache-common的同学可能不会轻易尝试,但在此还是强力推荐下,我觉得它不光是一个简单的工具类,也是在宣扬一种思想,在此我就从我喜欢的EventBus开始和大家分享下。


EventBus这个不是java才有的概念,由来已久了,我更喜欢把它理解为生产者与消费者的一种实现方式,也可以说是发布与订阅的实现,是系统解耦,高性能,高可扩展性的实现。

    首先就不贴一坨坨源码,讲下如何使用它吧,我相信很多同学对java的一项新技术首先是懂得如何使用,如何熟练使用,一些注意的点,如果还想更多的深入了解,就需要对源码有针对性的学习与研究了。

EventBus bus = new EventBus();
    bus.register(new Object() {
      @Subscribe
      @SuppressWarnings({"all"})
      public void accept(String str) {
         holder.set(str);
         deliveries.incrementAndGet();
         System.out.println("执行接受了吗?"+str);
      }
      @Subscribe
      public void doExt(Integer value){
    	  System.out.println("你好!"+value);
      }
      
    });
    
    EventBus gogalEventBus = new EventBus();
    gogalEventBus.register(new MyDo(){
    	@Subscribe
    	public void doAction(String name){
    		System.out.println("我做任何事情,但没有参数!");
    	}
    	@Subscribe
    	private void doProcess(String name){
    		System.out.println("我和能做任何事情!");
    	}
    });
    gogalEventBus.post("ppppp");
    
    String EVENT = "Hello!";
    bus.post(EVENT);
    bus.post(88888);

     

看到上面的示例代码会发现首先有个注册的过程(register),然后发送一个事件(post),但这个发送的事件由谁来处理呢?这个是subScribe注解来执行的,告诉我们谁来执行具体的逻辑。

 

 

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Beta
public @interface Subscribe/*订阅注解*/ {
}

  

class EventHandler/*事件处理者*/ {

  /** Object sporting the handler method. */
  private final Object target;
  /** Handler method. */
  private final Method method;

  /**
   * Creates a new EventHandler to wrap {@code method} on @{code target}.
   *
   * @param target  object to which the method applies.
   * @param method  handler method.
   */
  EventHandler(Object target, Method method) {
    Preconditions.checkNotNull(target,
        "EventHandler target cannot be null.");
    Preconditions.checkNotNull(method, "EventHandler method cannot be null.");

    this.target = target;
    this.method = method;
    method.setAccessible(true);
  }

  /**
   * Invokes the wrapped handler method to handle {@code event}.
   *
   * @param event  event to handle
   * @throws InvocationTargetException  if the wrapped method throws any
   *     {@link Throwable} that is not an {@link Error} ({@code Error} instances are
   *     propagated as-is).
   */
  public void handleEvent(Object event) throws InvocationTargetException {
    checkNotNull(event);
    try {
      method.invoke(target, new Object[] { event });//放射执行,更具有扩展通用
    } catch (IllegalArgumentException e) {
      throw new Error("Method rejected target/argument: " + event, e);
    } catch (IllegalAccessException e) {
      throw new Error("Method became inaccessible: " + event, e);
    } catch (InvocationTargetException e) {
      if (e.getCause() instanceof Error) {
        throw (Error) e.getCause();
      }
      throw e;
    }
  }

  @Override public String toString() {
    return "[wrapper " + method + "]";
  }

  @Override public int hashCode() {
    final int PRIME = 31;
    return (PRIME + method.hashCode()) * PRIME
        + System.identityHashCode(target);
  }

  @Override public boolean equals(@Nullable Object obj) {
    if (obj instanceof EventHandler) {
      EventHandler that = (EventHandler) obj;
      // Use == so that different equal instances will still receive events.
      // We only guard against the case that the same object is registered
      // multiple times
      return target == that.target && method.equals(that.method);
    }
    return false;
  }
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics