0Pricing
Clean Architecture & Design Patterns in Practice · 강의

프레젠터와 뷰 모델

프레젠터가 사용 사례의 데이터를 UI에 표시하기 적합한 뷰 모델로 변환하는 방식을 이해합니다.

프레젠터와 뷰 모델은(는) CoddyKit의 무료 Clean Architecture & Design Patterns in Practice 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Clean Architecture & Design Patterns in Practice 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Clean Architecture & Design Patterns in Practice 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Presenting Data to Users

In Clean Architecture, the outermost layer is dedicated to frameworks and drivers, which includes our user interface (UI). How do we effectively get data from our core business logic (Use Cases) to display on the screen?

This is where Presenters and View Models step in. They act as crucial adapters, bridging the gap between your application's core and its visual representation.

The Presenter's Purpose

A Presenter is an intermediary responsible for preparing data for the UI. It receives the 'raw' output from a Use Case, which often consists of business entities or specific data transfer objects (DTOs) from the application layer.

  • It transforms Use Case output into a UI-friendly format.
  • It handles presentation logic, such as formatting dates or combining strings.
  • It does NOT contain business rules or data access logic.

What is a View Model?

A View Model is a simple data structure specifically designed for a single view or UI component. It contains only the data needed to render that view, nothing more.

  • It's a 'dumb' data container with no behavior.
  • It only has properties relevant to the UI.
  • It decouples the UI from core domain objects, making the UI simpler.

Think of it as a blueprint for exactly what your screen needs to show.

Presenter & View Model in Action

Here's how Presenters and View Models typically work together in a Clean Architecture flow:

  1. A user action triggers a Use Case (e.g., 'Fetch User Details').
  2. The Use Case executes business logic and produces a result (e.g., a UserOutputData object).
  3. This result is passed to a Presenter.
  4. The Presenter transforms the UserOutputData into a UserViewModel.
  5. The UI then directly consumes and displays the UserViewModel.

Why This Separation Matters

Using Presenters and View Models provides significant architectural advantages:

  • UI Independence: Your core application logic doesn't need to know or care about how data is displayed.
  • Testability: Presenters are plain objects, making their transformation logic easy to unit test without needing a UI framework.
  • Flexibility: You can change your UI framework (e.g., from an old framework to a new one) without altering your Use Cases or Entities.

Example: Use Case Output

Let's consider a Use Case that fetches user details. It might return a data object like this, containing raw information:

public class UserOutputData {
    private String firstName;
    private String lastName;
    private String email;
    private long registrationTimestamp; // epoch seconds

    public UserOutputData(String firstName, String lastName, String email, long registrationTimestamp) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.registrationTimestamp = registrationTimestamp;
    }

    public String getFirstName() { return firstName; }
    public String getLastName() { return lastName; }
    public String getEmail() { return email; }
    public long getRegistrationTimestamp() { return registrationTimestamp; }
}

Designing the View Model

For our UI, we want to display the user's full name and a nicely formatted registration date. The raw timestamp from UserOutputData isn't directly displayable. So, we create a UserViewModel specifically for this purpose:

public class UserViewModel {
    private String fullName;
    private String formattedRegistrationDate;

    public UserViewModel(String fullName, String formattedRegistrationDate) {
        this.fullName = fullName;
        this.formattedRegistrationDate = formattedRegistrationDate;
    }

    public String getFullName() { return fullName; }
    public String getFormattedRegistrationDate() { return formattedRegistrationDate; }
}

Building the Presenter

Now, let's create a UserPresenter. Its job is to take the UserOutputData and convert it into the UserViewModel, handling any necessary formatting or presentation logic.

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class UserPresenter {
    public UserViewModel present(UserOutputData outputData) {
        // Combine first and last name for display
        String fullName = outputData.getFirstName() + " " + outputData.getLastName();

        // Format the timestamp into a readable date string
        Instant instant = Instant.ofEpochSecond(outputData.getRegistrationTimestamp());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
                                            .withZone(ZoneId.systemDefault());
        String formattedDate = formatter.format(instant);

        return new UserViewModel(fullName, formattedDate);
    }
}

Running the Presenter Flow

Here's a complete, runnable example demonstrating how a Use Case might return data, which is then processed by a Presenter and prepared for display by the UI.

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

// Simulate Use Case Output
class UserOutputData {
    private String firstName;
    private String lastName;
    private String email;
    private long registrationTimestamp;

    public UserOutputData(String firstName, String lastName, String email, long registrationTimestamp) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.registrationTimestamp = registrationTimestamp;
    }

    public String getFirstName() { return firstName; }
    public String getLastName() { return lastName; }
    public String getEmail() { return email; }
    public long getRegistrationTimestamp() { return registrationTimestamp; }
}

// View Model for UI
class UserViewModel {
    private String fullName;
    private String formattedRegistrationDate;

    public UserViewModel(String fullName, String formattedRegistrationDate) {
        this.fullName = fullName;
        this.formattedRegistrationDate = formattedRegistrationDate;
    }

    public String getFullName() { return fullName; }
    public String getFormattedRegistrationDate() { return formattedRegistrationDate; }
}

// Presenter logic
class UserPresenter {
    public UserViewModel present(UserOutputData outputData) {
        String fullName = outputData.getFirstName() + " " + outputData.getLastName();

        Instant instant = Instant.ofEpochSecond(outputData.getRegistrationTimestamp());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
                                            .withZone(ZoneId.systemDefault());
        String formattedDate = formatter.format(instant);

        return new UserViewModel(fullName, formattedDate);
    }
}

public class Main {
    public static void main(String[] args) {
        // 1. Simulate Use Case returning data
        UserOutputData userData = new UserOutputData(
            "Alice", "Smith", "alice@example.com", 1678886400L // March 15, 2023 12:00:00 PM UTC
        );

        // 2. Presenter transforms data
        UserPresenter presenter = new UserPresenter();
        UserViewModel viewModel = presenter.present(userData);

        // 3. UI "displays" the ViewModel
        System.out.println("Displaying User Profile:");
        System.out.println("Name: " + viewModel.getFullName());
        System.out.println("Registered: " + viewModel.getFormattedRegistrationDate());
    }
}

Test Your Knowledge

Which of the following best describes the primary role of a View Model in Clean Architecture?

Presenting Your Data Cleanly

In this lesson, we explored how Presenters and View Models play a vital role in the presentation layer of Clean Architecture.

  • Presenters act as data chefs, transforming Use Case output into UI-friendly formats.
  • View Models are simple, UI-specific data structures, containing only what's needed for display.
  • This separation boosts testability, maintains UI independence, and allows for flexible UI changes.

By using these patterns, your application's core logic remains pristine, unburdened by presentation details, making your system more robust and maintainable.

자주 묻는 질문

“프레젠터와 뷰 모델” 강의는 무료인가요?

네 — “프레젠터와 뷰 모델” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Clean Architecture & Design Patterns in Practice 강의 전체를 잠금 해제할 수 있습니다. Clean Architecture & Design Patterns in Practice 강의에는 총 4개의 강의가 포함되어 있습니다.

“프레젠터와 뷰 모델”에서 뭘 배우나요?

프레젠터가 사용 사례의 데이터를 UI에 표시하기 적합한 뷰 모델로 변환하는 방식을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Clean Architecture & Design Patterns in Practice을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Clean Architecture & Design Patterns in Practice을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Clean Architecture & Design Patterns in Practice은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“프레젠터와 뷰 모델” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Clean Architecture & Design Patterns in Practice 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Clean Architecture & Design Patterns in Practice 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 프레젠터와 뷰 모델
  2. 웹 프레임워크에 적용하기
  3. 프레젠테이션 계층 테스트
  4. 겸손한 객체와 뷰의 경계
← Clean Architecture & Design Patterns in Practice(으)로 돌아가기