google关于事件的生产者消费者模式实现例子

google使用生产者/消费者模式实现了事件的产生传播处理过程,也就是事件的产生与订阅。

这里通过一个简单的例子来测试运行。

1.定义事件

package com.event;

/**
*
* @author yangjianzhou
*
* Jan 24, 2015 11:19:09 AM
*
* 定义事件
*/
public class TestEvent {

private String name ;

public TestEvent(String name){
this.name = name ;
}

public String getName() {
return name;
}

}



2.定义事件监听器

package com.listener;

import com.event.TestEvent;
import com.google.common.eventbus.Subscribe;

/**
*
* @author yangjianzhou
*
* Jan 24, 2015 11:09:40 AM
*
* 监听事件,然后处理
*/
public class TestListener {

@Subscribe
public void processOne(TestEvent event){
System.out.println("this is processOne : " + event.getName());
}

@Subscribe
public void processTwo(TestEvent event){
System.out.println("this is processTwo : " + event.getName());
}

}



3.测试程序

package com.test;

import com.event.TestEvent;
import com.google.common.eventbus.EventBus;
import com.listener.TestListener;

/**
*
* @author yangjianzhou
*
* Jan 24, 2015 11:12:06 AM
*
* 事件测试
*/
public class TestEventListener {

public static void main(String[] args) {
EventBus eventBus = new EventBus();
TestEvent event = new TestEvent("yangjianzhou");
TestListener listener = new TestListener();
eventBus.register(listener);
eventBus.post(event);
}
}



4.运行结果:

this is processTwo : yangjianzhou
this is processOne : yangjianzhou

你可能感兴趣的:(java)