Порты ввода и вывода
Разберитесь, как порты ввода и вывода (интерфейсы) определяют границы взаимодействия между вариантами использования и внешними слоями.
«Порты ввода и вывода» — бесплатный урок Clean Architecture & Design Patterns in Practice на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Clean Architecture & Design Patterns in Practice, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Clean Architecture & Design Patterns in Practice содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
What are Input & Output Ports?
In Clean Architecture, "Ports" are crucial interfaces that define how different layers communicate. They act like contracts.
Think of them as the "sockets" of your application's core logic. They specify what goes in (Input) and what comes out (Output).
Defining Input Ports
An Input Port is an interface defined by the Use Case layer. It declares the methods that an external layer (like a UI controller) can call to interact with the Use Case.
- It's the "what you can do" contract for the Use Case.
- It ensures the Use Case doesn't know about the UI or external callers.
Input Port: User Login
Here's a simple Input Port for a user login feature. It defines the operations the Use Case expects.
public interface UserLoginInputPort {
void login(String username, String password);
}
public class UserLoginUseCase implements UserLoginInputPort {
@Override
public void login(String username, String password) {
// Business logic for login
System.out.println("Attempting login for: " + username);
if (username.equals("admin") && password.equals("pass")) {
System.out.println("Login successful!");
} else {
System.out.println("Login failed.");
}
}
public static void main(String[] args) {
UserLoginInputPort loginService = new UserLoginUseCase();
loginService.login("admin", "pass");
loginService.login("user", "123");
}
}Defining Output Ports
An Output Port is also an interface, defined by the Use Case layer. It declares the methods that the Use Case will call to deliver results or interact with external services (like a database or UI presenter).
- It's the "what I need to tell you" contract.
- It keeps the Use Case unaware of specific implementations (e.g., how results are displayed).
Output Port: Login Presenter
This Output Port defines how the login result should be presented or handled. The Use Case calls these methods, but doesn't know how they are implemented.
public interface UserLoginOutputPort {
void presentLoginSuccess(String username);
void presentLoginFailure(String message);
}
public class ConsolePresenter implements UserLoginOutputPort {
@Override
public void presentLoginSuccess(String username) {
System.out.println("Welcome, " + username + "!");
}
@Override
public void presentLoginFailure(String message) {
System.out.println("Error: " + message);
}
public static void main(String[] args) {
UserLoginOutputPort presenter = new ConsolePresenter();
presenter.presentLoginSuccess("Alice");
presenter.presentLoginFailure("Invalid credentials.");
}
}How Use Cases Use Ports
The Use Case (or Interactor) depends on these port interfaces. It takes an Input Port as its public method and receives an Output Port through its constructor or method parameters.
This means the Use Case only knows about abstractions, not concrete implementations.
Use Case Connecting Ports
Here, our UserLoginUseCase now uses both ports. Notice it doesn't know if it's talking to a web UI, a mobile app, or a console!
public interface UserLoginInputPort {
void login(String username, String password);
}
public interface UserLoginOutputPort {
void presentLoginSuccess(String username);
void presentLoginFailure(String message);
}
public class UserLoginUseCase implements UserLoginInputPort {
private final UserLoginOutputPort outputPort;
public UserLoginUseCase(UserLoginOutputPort outputPort) {
this.outputPort = outputPort;
}
@Override
public void login(String username, String password) {
if (username.equals("admin") && password.equals("pass")) {
outputPort.presentLoginSuccess(username);
} else {
outputPort.presentLoginFailure("Invalid credentials.");
}
}
public static void main(String[] args) {
// In real app, this would be wired by a framework
UserLoginOutputPort presenter = new ConsolePresenter(); // From Scene 5
UserLoginInputPort loginService = new UserLoginUseCase(presenter);
loginService.login("admin", "pass");
loginService.login("user", "wrong");
}
}
class ConsolePresenter implements UserLoginOutputPort {
@Override
public void presentLoginSuccess(String username) {
System.out.println("Welcome, " + username + "!");
}
@Override
public void presentLoginFailure(String message) {
System.out.println("Error: " + message);
}
}Ports and the Dependency Rule
The use of Ports perfectly adheres to the Dependency Rule. The Use Case layer (core business logic) depends on interfaces (the Ports).
The outer layers (like UI or databases) then implement these interfaces, providing the concrete details without the core knowing about them.
Why Use Ports?
Ports offer powerful advantages:
- Decoupling: The Use Case is isolated from UI, database, or external services.
- Testability: You can easily mock or stub these interfaces for robust unit testing of Use Cases.
- Flexibility: You can swap out implementations (e.g., change database) without touching core logic.
- Clarity: They clearly define the boundaries and interactions of your application's core.
Quick Check: Port Roles
Consider the roles of Input and Output Ports in Clean Architecture.
Recap: Ports as Boundaries
We learned that Input Ports are interfaces defining what a Use Case expects, acting as entry points.
Output Ports are interfaces defining what a Use Case delivers or needs from external services.
Together, they enforce the Dependency Rule, ensuring our core business logic remains independent, testable, and flexible.
Часто задаваемые вопросы
Урок «Порты ввода и вывода» бесплатный?
Да — полный текст урока «Порты ввода и вывода» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Clean Architecture & Design Patterns in Practice, подпишись на CoddyKit PRO. Курс Clean Architecture & Design Patterns in Practice содержит 4 уроков всего.
Чему я научусь в уроке «Порты ввода и вывода»?
Разберитесь, как порты ввода и вывода (интерфейсы) определяют границы взаимодействия между вариантами использования и внешними слоями. Ты практикуешь Clean Architecture & Design Patterns in Practice с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Clean Architecture & Design Patterns in Practice?
Предыдущий опыт не требуется. Clean Architecture & Design Patterns in Practice на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Порты ввода и вывода»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Clean Architecture & Design Patterns in Practice?
Да. Каждый урок Clean Architecture & Design Patterns in Practice включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Проектирование бизнес-сущностей
- Реализация вариантов использования (интеракторов)
- Порты ввода и вывода
- Обеспечение бизнес-правил с помощью инвариантов