稍微回想一下计算机硬件的工作原理我们便不难发现,整个计算机的工作过程其实就是一个对事件的处理过程。当你点击鼠标、敲击键盘或者插上U盘时,计算机便以中断的形式处理各种
public abstract class Event { private final UUID id; private final DateTime createdTime; public Event() { this.id = UUID.randomUUID(); this.createdTime = new DateTime(); } }
public final class CustomerArrivedEvent extends Event { private final int customerNumber; public CustomerArrivedEvent(int customerNumber) { super(); this.customerNumber = customerNumber; } }
public class Order { public Order(EventPublisher eventPublisher) { //create order //… eventPublisher.publish(new OrderPlacedEvent()); } }
public class Order { public Order() { //create order //... EventPublisher.publish(new OrderPlacedEvent()); } }
public class Order { private List<Event> events; public Order() { //create order //... events.add(new OrderPlacedEvent()); } public List<Event> getEvents() { return events; } public void clearEvents() { events.clear(); } }
@Test public void shouldPublishEventWhenCreateOrder() { Order order = new Order(); List<Event> events = order.getEvents(); assertEquals(1, events.size()); Event event = events.get(0); assertTrue(event instanceof OrderPlacedEvent); }
public class OrderRepository { private EventPublisher eventPublisher; public void save(Order order) { //save the order //... List<Event> events = order.getEvents(); events.forEach(event -> eventPublisher.publish(event)); order.clearEvents(); } }