Clean Architecture & Design Patterns in Practice · 课时

事件驱动的整洁架构

将事件驱动模式集成到整洁架构中,使用领域事件增强解耦性和可扩展性。

第 2 / 4 课12 个步骤

事件驱动的整洁架构 是 CoddyKit 上的免费 Clean Architecture & Design Patterns in Practice 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Clean Architecture & Design Patterns in Practice 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Clean Architecture & Design Patterns in Practice 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Intro to Event-Driven Clean Arch

Welcome to Event-Driven Clean Architecture! In complex systems, parts often need to react to things happening elsewhere without being tightly coupled.

This lesson explores how to integrate event-driven patterns into your Clean Architecture, using domain events to enhance decoupling and scalability, while strictly adhering to the Dependency Rule.

What are Domain Events?

A Domain Event is something that happened in the domain that domain experts care about. It's an immutable fact, a record of an occurrence, like 'Order Placed' or 'User Registered'.

  • They represent a change in the state of the domain.
  • They are typically named in the past tense (e.g., OrderPlaced).
  • They should be simple data structures, containing only relevant information about the event.

Events and the Dependency Rule

In Clean Architecture, the Dependency Rule states that dependencies must flow inwards. Domain events fit perfectly:

  • Entities can raise events, but don't know who handles them.
  • Use Cases orchestrate entities and can publish events after an operation.
  • Interface Adapters (e.g., presenters, external service gateways) can subscribe to and handle events from inner layers.

This maintains strict separation, as inner layers remain unaware of outer layer specifics.

Implementing a Domain Event

A domain event is essentially a data transfer object (DTO) that carries information about what happened. It's good practice to have a common interface for all domain events.

Here's a simple Java interface:

public interface DomainEvent {
  long occurredOn();
}

Code: Concrete Domain Event

Let's create a specific domain event: OrderPlacedEvent. It holds the orderId and the timestamp of when it occurred.

Try running this simple definition:

public class OrderPlacedEvent implements DomainEvent {
  private final String orderId;
  private final long occurredOn;

  public OrderPlacedEvent(String orderId) {
    this.orderId = orderId;
    this.occurredOn = System.currentTimeMillis();
  }

  public String getOrderId() {
    return orderId;
  }

  @Override
  public long occurredOn() {
    return occurredOn;
  }

  public static void main(String[] args) {
    OrderPlacedEvent event = new OrderPlacedEvent("ORD-123");
    System.out.println("Order event for: " + event.getOrderId());
  }
}

The Event Publisher

To publish events, we need an Event Publisher (also known as an Event Dispatcher or Event Bus). This component takes a domain event and dispatches it to all registered handlers.

It acts as a mediator, decoupling the event source from its consumers. The Use Case will depend on this publisher interface, not on specific handlers.

Code: Event Publisher Interface

Here's an interface for our EventPublisher. We'll also need a way for handlers to register themselves.

public interface EventPublisher {
  void publish(DomainEvent event);
  <T extends DomainEvent> void subscribe(Class<T> eventType, EventHandler<T> handler);
}

Code: In-Memory Event Publisher

A simple in-memory implementation for demonstration purposes. In a real application, this might use a message queue (e.g., Kafka, RabbitMQ) for persistence and distribution.

Run this to see the basic publisher in action:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public interface DomainEvent { long occurredOn(); }
public interface EventHandler<T extends DomainEvent> { void handle(T event); }

public class OrderPlacedEvent implements DomainEvent {
  private final String orderId; private final long occurredOn;
  public OrderPlacedEvent(String orderId) {
    this.orderId = orderId; this.occurredOn = System.currentTimeMillis();
  }
  public String getOrderId() { return orderId; }
  @Override public long occurredOn() { return occurredOn; }
}

public class SimpleEventPublisher implements EventPublisher {
  private final Map<Class<? extends DomainEvent>, List<EventHandler<?>>> subscribers = new HashMap<>();

  @Override
  public void publish(DomainEvent event) {
    List<EventHandler<?>> handlers = subscribers.get(event.getClass());
    if (handlers != null) {
      for (EventHandler handler : handlers) {
        // Unchecked cast is safe due to type checking during subscription
        ((EventHandler<DomainEvent>) handler).handle(event);
      }
    }
  }

  @Override
  public <T extends DomainEvent> void subscribe(Class<T> eventType, EventHandler<T> handler) {
    subscribers.computeIfAbsent(eventType, k -> new ArrayList<>()).add(handler);
  }

  public static void main(String[] args) {
    SimpleEventPublisher publisher = new SimpleEventPublisher();
    publisher.subscribe(OrderPlacedEvent.class, event -> {
      System.out.println("Handler 1: Order " + event.getOrderId() + " placed!");
    });
    publisher.subscribe(OrderPlacedEvent.class, event -> {
      System.out.println("Handler 2: Notifying ops for order " + event.getOrderId());
    });

    OrderPlacedEvent event = new OrderPlacedEvent("DEMO-456");
    publisher.publish(event);
  }
}

Integrating Use Cases & Handlers

Now, let's see how a Use Case publishes an event and how an Event Handler (residing in, for example, the Interface Adapters layer) reacts to it. The Use Case remains decoupled from the handler.

This design allows new handlers to be added without modifying the Use Case.

Code: Full Event-Driven Flow

This example demonstrates a PlaceOrderUseCase publishing an OrderPlacedEvent, which is then handled by an OrderEmailNotifier.

Notice how PlaceOrderUseCase only depends on EventPublisher, not the specific notifier.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// Domain Layer Interfaces & Classes
interface DomainEvent { long occurredOn(); }
class OrderPlacedEvent implements DomainEvent {
  private final String orderId; private final long occurredOn;
  public OrderPlacedEvent(String orderId) {
    this.orderId = orderId; this.occurredOn = System.currentTimeMillis();
  }
  public String getOrderId() { return orderId; }
  @Override public long occurredOn() { return occurredOn; }
}

// Application Layer Interfaces & Classes
interface EventPublisher {
  void publish(DomainEvent event);
  <T extends DomainEvent> void subscribe(Class<T> eventType, EventHandler<T> handler);
}
interface EventHandler<T extends DomainEvent> { void handle(T event); }

// Use Case (Application Layer)
class PlaceOrderUseCase {
  private final EventPublisher eventPublisher;

  public PlaceOrderUseCase(EventPublisher eventPublisher) {
    this.eventPublisher = eventPublisher;
  }

  public void execute(String orderDetails) {
    // Simulate order creation logic
    String newOrderId = "ORD-" + System.nanoTime();
    System.out.println("Order " + newOrderId + " created with details: " + orderDetails);

    // Publish domain event
    eventPublisher.publish(new OrderPlacedEvent(newOrderId));
  }
}

// Infrastructure/Interface Adapters Layer Implementation
class SimpleEventPublisher implements EventPublisher {
  private final Map<Class<? extends DomainEvent>, List<EventHandler<?>>> subscribers = new HashMap<>();

  @Override
  public void publish(DomainEvent event) {
    List<EventHandler<?>> handlers = subscribers.get(event.getClass());
    if (handlers != null) {
      for (EventHandler handler : handlers) {
        ((EventHandler<DomainEvent>) handler).handle(event);
      }
    }
  }

  @Override
  public <T extends DomainEvent> void subscribe(Class<T> eventType, EventHandler<T> handler) {
    subscribers.computeIfAbsent(eventType, k -> new ArrayList<>()).add(handler);
  }
}

class OrderEmailNotifier implements EventHandler<OrderPlacedEvent> {
  @Override
  public void handle(OrderPlacedEvent event) {
    System.out.println("Email Notifier: Sending email for order " + event.getOrderId());
  }
}

class InventoryUpdater implements EventHandler<OrderPlacedEvent> {
  @Override
  public void handle(OrderPlacedEvent event) {
    System.out.println("Inventory Updater: Updating inventory for order " + event.getOrderId());
  }
}

public class Main {
  public static void main(String[] args) {
    SimpleEventPublisher publisher = new SimpleEventPublisher();

    // Register handlers
    publisher.subscribe(OrderPlacedEvent.class, new OrderEmailNotifier());
    publisher.subscribe(OrderPlacedEvent.class, new InventoryUpdater());

    // Create use case with publisher dependency
    PlaceOrderUseCase placeOrderUseCase = new PlaceOrderUseCase(publisher);

    // Execute use case, which publishes the event
    placeOrderUseCase.execute("Laptop, Quantity: 1");
    placeOrderUseCase.execute("Keyboard, Quantity: 2");
  }
}

Quick Check: Domain Events

When integrating domain events into Clean Architecture, what is the primary benefit of having Use Cases publish events rather than directly calling other services?

Recap: Event-Driven Clean Arch

In this lesson, we explored Event-Driven Clean Architecture. You learned:

  • Domain Events are immutable facts representing significant occurrences.
  • They enable decoupling, allowing Use Cases to publish events without knowing their subscribers.
  • Event Publishers mediate event dispatch to Event Handlers.
  • This pattern supports scalability and extensibility, making systems easier to evolve while adhering to the Dependency Rule.

By leveraging domain events, your Clean Architecture can become even more robust and adaptable.

免费开始

用 AI 导师学习 Clean Architecture & Design Patterns in Practice — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
12
课程
48

常见问题解答

「事件驱动的整洁架构」课时是免费的吗?

是的 — 「事件驱动的整洁架构」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Clean Architecture & Design Patterns in Practice 课程的其余内容,请升级到 CoddyKit PRO。 Clean Architecture & Design Patterns in Practice 课程共包含 4 节课。

「事件驱动的整洁架构」这节课中我会学到什么?

将事件驱动模式集成到整洁架构中,使用领域事件增强解耦性和可扩展性。 你通过在浏览器中直接运行的动手代码来练习 Clean Architecture & Design Patterns in Practice,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Clean Architecture & Design Patterns in Practice 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Clean Architecture & Design Patterns in Practice 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「事件驱动的整洁架构」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Clean Architecture & Design Patterns in Practice 课中编写并运行代码吗?

能。每节 Clean Architecture & Design Patterns in Practice 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 处理横切关注点
  2. 事件驱动的整洁架构
  3. 微服务中的整洁架构
  4. 整洁架构中的 CQRS
← 返回 Clean Architecture & Design Patterns in Practice