Guava观察者

This commit is contained in:
2020-03-05 16:40:37 +08:00
parent 17796c4639
commit 7f6d42c06d
2 changed files with 52 additions and 0 deletions

View File

@@ -0,0 +1,28 @@
package top.fjy8018.designpattern.pattern.behavior.observer.guava;
import com.google.common.eventbus.Subscribe;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* Guava事件监听器
* {@link EventBus} 使用内部对象 {@link SubscriberRegistry} 内部使用 {@link ConcurrentMap} 存储订阅者
* 同时使用 {@link CopyOnWriteArraySet} 保证线程安全和订阅者唯一
* 故{@link com.google.common.eventbus.Subscriber}
* 重写了 {@link com.google.common.eventbus.Subscriber#equals(Object)}
* 和 {@link com.google.common.eventbus.Subscriber#hashCode()} 方法
*
* @author F嘉阳
* @date 2020/3/5 15:56
*/
@Slf4j
public class GuavaEvent {
@Subscribe
public void subscribe(String str) {
// 业务逻辑
log.info("执行订阅方法,传入参数是:{}", str);
}
}

View File

@@ -0,0 +1,24 @@
package top.fjy8018.designpattern.pattern.behavior.observer;
import com.google.common.eventbus.EventBus;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import top.fjy8018.designpattern.pattern.behavior.observer.guava.GuavaEvent;
/**
* @author F嘉阳
* @date 2020/3/5 15:58
*/
@Slf4j
class GuavaEventTest {
@Test
void subscribe() {
EventBus eventBus = new EventBus();
GuavaEvent event = new GuavaEvent();
// 注册
eventBus.register(event);
eventBus.post("提交事件的内容");
}
}