[Swift] Thực hành Clean Architecture ① (Tầng Domain)
Bài đăng này đã không được cập nhật trong 10 năm
Lời mở đầu
Dựa theo cuốn sách "Clean Architecture" đang khá hot thời gian gần đây, mình xin được tóm tắt với các bạn từng phần của nó. Ở phần 1 là tầng Domain
Cách phần sẽ làm
- Tầng UI
- View
- ViewController
- Presenter
- Tầng Domain
- UseCase
- Repository
- Entity
- Tầng Data
- Repository
- Entity
- DataStore
Giải thích ví dụ
Usecase này sẽ access để lấy thông tin của User
| Layer | Category | Class Name | Description |
|---|---|---|---|
| Domain | Entity | User | Class quản lý thông tin User (mail, birth) |
| Repository | UserRepository | Interface của User Infomation | |
| Usecase | UserUseCase | Class thực hiện Logic | |
| Data | Repository | UserRepositorylmpl | Class để thực hiện access đến User Info |
1. Về Entity của tầng Domain
Sử dụng Class để lưu thông tin user (mail, ngày sinh)
import Foundation
class User: NSObject {
var mailAddress = ""
var birthDay = ""
}
2. Repository của Domain
Interface (protocol) để cung cấp giải pháp access User Infomation
import Foundation
protocol UserRepository: class {
func store(user: User)
func user(userID: NSInteger) -> User
func users() -> [User]
func delete(userID: NSInteger)
}
3. Repository của tầng Data
Là Class thực thi UserRepository Protocol Sử dụng để xử lý các thao tác trên thông tin user , có thể để trong app hay ở Server đều được
class UserRepositoryImpl: UserRepository {
func store(user: User) {
//TODO: lưu thông tin user vào đâu đó
}
func user(userID: NSInteger) -> User {
//TODO: Lấy thông tin người dùng từ đâu đó
return User()
}
func users() -> [User] {
//TODO: Lấy thông tin người dùng từ đâu đó
return []
}
func delete(userID: NSInteger) {
//TODO: Xoá thông tin người dùng
}
}
4. UseCase của tầng Domain
import Foundation
class UserUsecase: NSObject {
let repository: UserRepository
init(repository: UserRepository) {
self.repository = repository
super.init()
}
//Lưu MailAddress
func storeMailAddressByID(userID: NSInteger, mailAddress: String) {
let user = repository.user(userID)
user.mailAddress = mailAddress
repository.store(user)
}
//Lấy MailAddress
func findMailAddressByID(userID: NSInteger) -> String {
return repository.user(userID).mailAddress
}
//Lưu Ngày Tháng Năm Sinh
func storeBirthDayByID(userID: NSInteger, birthDaty: String) {
let user = repository.user(userID)
user.birthDay = birthDaty
repository.store(user)
}
//Lấy Ngày Tháng Năm Sinh
func findBirthDayByID(userID: NSInteger) -> String {
return repository.user(userID).birthDay
}
}
Tổng kết
Point ở đấy chính là Phần Repository của tầng Domain:
- Để access vào Data, ta cần acccess thông qua Repository của tầng Domain
- Client khi access vào Data ko cần quan tâm việc dữ liệu lưu ở đâu, Server (thông qua API) hay là ở trong App (CoreData, UserDefault)
All rights reserved