ตัวนำเสนอและโมเดลมุมมอง
ทำความเข้าใจว่าตัวนำเสนอจัดรูปแบบข้อมูลจากกรณีใช้งานเป็นโมเดลมุมมองที่เหมาะสำหรับแสดงผลใน UI อย่างไร
ตัวนำเสนอและโมเดลมุมมอง เป็นบทเรียน Clean Architecture & Design Patterns in Practice ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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:
- A user action triggers a Use Case (e.g., 'Fetch User Details').
- The Use Case executes business logic and produces a result (e.g., a
UserOutputDataobject). - This result is passed to a Presenter.
- The Presenter transforms the
UserOutputDatainto a UserViewModel. - 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.
คำถามที่พบบ่อย
บทเรียน “ตัวนำเสนอและโมเดลมุมมอง” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ตัวนำเสนอและโมเดลมุมมอง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Clean Architecture & Design Patterns in Practice ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Clean Architecture & Design Patterns in Practice มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ตัวนำเสนอและโมเดลมุมมอง”
ทำความเข้าใจว่าตัวนำเสนอจัดรูปแบบข้อมูลจากกรณีใช้งานเป็นโมเดลมุมมองที่เหมาะสำหรับแสดงผลใน UI อย่างไร คุณปฏิบัติ Clean Architecture & Design Patterns in Practice ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Clean Architecture & Design Patterns in Practice หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Clean Architecture & Design Patterns in Practice บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “ตัวนำเสนอและโมเดลมุมมอง” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Clean Architecture & Design Patterns in Practice นี้ได้ไหม
ได้ บทเรียน Clean Architecture & Design Patterns in Practice ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ตัวนำเสนอและโมเดลมุมมอง
- การปรับใช้กับเว็บเฟรมเวิร์ก
- การทดสอบเลเยอร์การนำเสนอ
- อ็อบเจ็กต์ถ่อมตนและขอบเขตมุมมอง