事件驱动架构模式
public class EventDriven {
/**
* 事件驱动架构模式:
* Send and notify state changes of your objects to other applications
* using an Event-driven Architecture.
* 使用事件驱动的架构来发送通知【此对象状态的变更】给应用程序中的其他组件,解耦了事件源和事件处理器。
*/
@Test
public void all() {
final EventDispatcher eventDispatcher = EventDispatcherImpl.builder().build();
eventDispatcher.register(UserCreateEvent.class, new UserCreateHandler());
eventDispatcher.dispacher(UserCreateEvent.of(User.of(Long.valueOf(1), "zxd")));
}
}
/**
* 1)事件抽象
*/
interface Event {
Class<? extends Event> type();
}
abstract class BaseEvent implements Event {
@Override
public Class<? extends Event> type() {
return getClass();
}
}
/**
* 2)事件处理器抽象
*/
interface EventHandler<T extends Event> {
void handle(T event);
}
/**
* 3)事件调度器抽象
*/
interface EventDispatcher {
<E extends Event> void register(Class<? extends Event> type, EventHandler<E> hanlder);
<E extends Event> void dispacher(E event);
}
/**
* 4)事件调度器实现
*/
@Slf4j
@Builder
class EventDispatcherImpl implements EventDispatcher {
@Default
private final ConcurrentMap<Class<? extends Event>, EventHandler<? extends Event>> HANDLERS = new ConcurrentHashMap<>();
@Override
public <E extends Event> void register(Class<? extends Event> type, EventHandler<E> hanlder) {
HANDLERS.putIfAbsent(type, hanlder);
}
@Override
public <E extends Event> void dispacher(E event) {
final EventHandler<E> handler = (EventHandler<E>) HANDLERS.get(event.getClass());
if (handler != null) {
handler.handle(event);
} else {
log.error("no handler for event {}", event);
}
}
}
@Value(staticConstructor = "of")
class User {
private Long id;
private String name;
}
/**
* 5)具体的事件
*/
@Value(staticConstructor = "of")
class UserCreateEvent extends BaseEvent {
private User user;
}
/**
* 6)具体的事件处理器
*/
@Slf4j
class UserCreateHandler implements EventHandler<UserCreateEvent> {
@Override
public void handle(UserCreateEvent event) {
log.info("id:{} name:{}", event.getUser().getId(), event.getUser().getName());
}
}
原文地址:https://www.cnblogs.com/zhuxudong/p/10223535.html
时间: 2024-10-13 21:11:46