0Pricing
Clean Architecture & Design Patterns in Practice · 课时

适配 Web 框架

学习将整洁架构与常用 Web 框架(例如 Spring、ASP.NET、Django)集成的策略,同时避免与这些框架耦合。

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

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

Frameworks & Clean Architecture

Web frameworks like Spring, Django, or ASP.NET are powerful tools for building applications. But how do they fit into a Clean Architecture?

The challenge is to leverage their features without letting them dictate or couple to our core business logic. This lesson explores strategies to achieve that separation.

Avoiding Framework Coupling

Coupling occurs when one part of your code is highly dependent on another. In Clean Architecture, we want our inner layers (Entities, Use Cases) to be independent.

  • If your Use Cases directly import Spring annotations or Django models, they are coupled.
  • This makes it hard to change frameworks, test core logic, or reuse components.

The Dependency Rule Applied

Remember the Dependency Rule? Dependencies can only flow inwards. This is crucial for framework integration.

  • Your core business logic (Entities, Use Cases) should never know about the web framework.
  • The web framework (an outer layer) can and should depend on your core logic.

We need a bridge that respects this rule.

Presenters & Adapters Bridge

The 'Frameworks & Drivers' layer is where our web framework lives. To communicate with the inner 'Interface Adapters' layer (which contains Presenters and Controllers), we use specific patterns:

  • Adapters: Translate incoming framework-specific requests into a format our Use Cases understand.
  • Presenters: Format the output from Use Cases into a structure suitable for the web framework's views or JSON responses.

The Web Controller as an Adapter

In web applications, the framework's controller often serves as the primary adapter. Its job is to:

  1. Receive HTTP requests (e.g., from a browser or API client).
  2. Extract relevant data from the request.
  3. Convert this data into a simple object (a Request Model) that matches the Use Case's Input Port.
  4. Call the Use Case.
  5. Receive output from the Use Case (a Response Model).
  6. Pass this output to a Presenter to format the final HTTP response.

Defining an Input Port

Our Use Cases expose simple interfaces, called Input Ports. The web controller will depend on this interface, not the concrete Use Case implementation. This keeps the Use Case truly independent.

Here's an example of an Input Port and its corresponding Request object:

interface AddItemInputPort {
    void execute(AddItemRequest request);
}

class AddItemRequest {
    public final String itemName;
    public final double price;

    public AddItemRequest(String itemName, double price) {
        this.itemName = itemName;
        this.price = price;
    }
}

public class Main {
    public static void main(String[] args) {
        // These are just definitions, not runnable logic on their own.
        // We'll see them in action soon!
        System.out.println("InputPort and Request defined.");
    }
}

Implementing a Use Case

The actual business logic resides within the Use Case. It implements the AddItemInputPort and performs the operation, completely unaware of how it was invoked (e.g., by a web request, a CLI, or a message queue).

interface AddItemInputPort {
    void execute(AddItemRequest request);
}

class AddItemRequest {
    public final String itemName;
    public final double price;

    public AddItemRequest(String itemName, double price) {
        this.itemName = itemName;
        this.price = price;
    }
}

class AddItemUseCase implements AddItemInputPort {
    @Override
    public void execute(AddItemRequest request) {
        System.out.println("Use Case: Processing item '" +
                           request.itemName + "' with price $" +
                           request.price + ".");
        // In a real application, this would involve business rules,
        // interacting with entities, and potentially repositories.
    }
}

public class Main {
    public static void main(String[] args) {
        AddItemInputPort useCase = new AddItemUseCase();
        AddItemRequest request = new AddItemRequest("Fancy Pen", 15.75);
        useCase.execute(request);
    }
}

Web Controller Adapter in Action

Now, let's see how a simplified web controller (acting as an adapter) uses our Use Case. Notice it only interacts with the AddItemInputPort interface, not the concrete AddItemUseCase class.

interface AddItemInputPort {
    void execute(AddItemRequest request);
}

class AddItemRequest {
    public final String itemName;
    public final double price;
    public AddItemRequest(String itemName, double price) {
        this.itemName = itemName;
        this.price = price;
    }
}

class AddItemUseCase implements AddItemInputPort {
    @Override
    public void execute(AddItemRequest request) {
        System.out.println("Use Case processed: " + request.itemName);
    }
}

// This class simulates a web framework controller
class WebFrameworkController {
    private final AddItemInputPort addItemInputPort;

    // Controller depends on the Input Port interface
    public WebFrameworkController(AddItemInputPort addItemInputPort) {
        this.addItemInputPort = addItemInputPort;
    }

    // This method simulates handling an HTTP POST request
    public String handleHttpRequest(String name, double cost) {
        System.out.println("Controller received HTTP request for: " + name);
        AddItemRequest request = new AddItemRequest(name, cost);
        addItemInputPort.execute(request); // Delegate to Use Case
        return "HTTP Response: Item '" + name + "' added.";
    }
}

public class Main {
    public static void main(String[] args) {
        // Setup: Inject the Use Case into the Controller
        AddItemInputPort useCase = new AddItemUseCase();
        WebFrameworkController controller = new WebFrameworkController(useCase);

        // Simulate an incoming web request
        String response = controller.handleHttpRequest("Notebook", 8.99);
        System.out.println(response);
    }
}

Benefits of Decoupling Frameworks

This adapter-based approach offers significant advantages:

  • Testability: Use Cases can be tested in isolation, without needing to boot up the entire web framework.
  • Maintainability: Changes or upgrades to your web framework have minimal impact on your core business logic.
  • Flexibility: You could swap out your web framework for another (e.g., from Spring to JAX-RS) with changes only in the outer 'Frameworks & Drivers' layer.
  • Framework Independence: Your valuable business rules are not tied to a specific technology vendor.

Check Your Understanding

Which of the following best describes the role of a web controller when integrating a Clean Architecture application with a web framework?

Recap: Framework Integration

In this lesson, we explored how to integrate web frameworks into a Clean Architecture application while maintaining crucial separation:

  • We treat the web framework as an outer layer that depends on our core logic, not the other way around.
  • Controllers in the web framework act as adapters, translating web requests into Use Case Input Ports and formatting Use Case output.
  • This approach ensures high testability, maintainability, and framework independence for your core application.

常见问题解答

「适配 Web 框架」课时是免费的吗?

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

「适配 Web 框架」这节课中我会学到什么?

学习将整洁架构与常用 Web 框架(例如 Spring、ASP.NET、Django)集成的策略,同时避免与这些框架耦合。 你通过在浏览器中直接运行的动手代码来练习 Clean Architecture & Design Patterns in Practice,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

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

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

「适配 Web 框架」课时需要多长时间?

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

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

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

此课程中的所有课时

  1. 表示器与视图模型
  2. 适配 Web 框架
  3. 测试表示层
  4. 谦卑对象与视图边界
← 返回 Clean Architecture & Design Patterns in Practice