随着 HarmonyOS 应用复杂度提升,业务逻辑、UI 交互、数据流散落在各处,代码耦合严重、难以测试、维护成本高。架构模式通过分层解耦、职责分离、单向数据流,让代码更清晰、更可测、更易扩展。
经典三层架构:
// ❌ 反模式:UI 层直接访问数据库
@Component
struct BadExample {
async loadData() {
const db = relationalStore.getRdbStore(...) // UI 层不应知道数据库细节
}
}
// ✅ 正确:通过 Repository 隔离
export class UserRepository {
private db: relationalStore.RdbStore
async getUsers(): Promise<User[]> {
const result = await this.db.query('users')
return result.rows.map(row => new User(row))
}
}
@Component
struct GoodExample {
private repo = new UserRepository()
@State users: User[] = []
async aboutToAppear() {
this.users = await this.repo.getUsers() // UI 只关心业务对象
}
}MVVM(Model-View-ViewModel)将 UI 状态抽离到 ViewModel,通过数据绑定驱动视图更新。
User、Product)// Model
export class Todo {
constructor(public id: string, public text: string, public done: boolean) {}
}
// ViewModel
export class TodoViewModel {
@State todos: Todo[] = []
@State inputText: string = ''
private repo = new TodoRepository()
async loadTodos() {
this.todos = await this.repo.getAll()
}
async addTodo() {
if (!this.inputText.trim()) return
const newTodo = await this.repo.create(this.inputText)
this.todos = [...this.todos, newTodo]
this.inputText = ''
}
async toggleTodo(id: string) {
const todo = this.todos.find(t => t.id === id)
if (todo) {
todo.done = !todo.done
await this.repo.update(todo)
this.todos = [...this.todos] // 触发刷新
}
}
}
// View
@Component
struct TodoListView {
@State vm: TodoViewModel = new TodoViewModel()
aboutToAppear() {
this.vm.loadTodos()
}
build() {
Column() {
TextInput({ text: this.vm.inputText })
.onChange(v => this.vm.inputText = v)
Button('添加').onClick(() => this.vm.addTodo())
List() {
ForEach(this.vm.todos, (todo: Todo) => {
ListItem() {
Row() {
Checkbox().select(todo.done)
.onChange(() => this.vm.toggleTodo(todo.id))
Text(todo.text).decoration(todo.done ? TextDecorationType.LineThrough : TextDecorationType.None)
}
}
}, (todo: Todo) => todo.id)
}
}
}
}优势:
陷阱:
@Link 过多导致数据流向不清晰受 Redux/Vuex 启发,状态驱动 UI 强调单向数据流:Action → Reducer → State → View。
{ type: 'ADD_TODO', text: '...' })// Action 定义
type Action =
| { type: 'ADD_TODO', text: string }
| { type: 'TOGGLE_TODO', id: string }
| { type: 'SET_TODOS', todos: Todo[] }
// State 定义
interface AppState {
todos: Todo[]
}
// Reducer
function todoReducer(state: AppState, action: Action): AppState {
switch (action.type) {
case 'ADD_TODO':
return { ...state, todos: [...state.todos, new Todo(Date.now().toString(), action.text, false)] }
case 'TOGGLE_TODO':
return {
...state,
todos: state.todos.map(t => t.id === action.id ? { ...t, done: !t.done } : t)
}
case 'SET_TODOS':
return { ...state, todos: action.todos }
default:
return state
}
}
// Store
class Store {
@State private state: AppState = { todos: [] }
dispatch(action: Action) {
this.state = todoReducer(this.state, action)
}
getState(): AppState {
return this.state
}
}
// View
@Component
struct TodoApp {
private store = new Store()
build() {
Column() {
Button('添加').onClick(() => this.store.dispatch({ type: 'ADD_TODO', text: '新任务' }))
List() {
ForEach(this.store.getState().todos, (todo: Todo) => {
ListItem() {
Text(todo.text).onClick(() => this.store.dispatch({ type: 'TOGGLE_TODO', id: todo.id }))
}
})
}
}
}
}场景 | 推荐架构 | 原因 |
|---|---|---|
简单工具类应用 | 分层架构 | 无需复杂状态管理,三层足够 |
表单密集、交互复杂 | MVVM | ViewModel 集中管理表单状态 |
多页面共享状态 | 状态驱动 UI | 全局 Store 避免状态分散 |
实时协作、撤销重做 | 状态驱动 UI | Action 可序列化、可回放 |
@State 即可,不要为了架构而架构架构模式不是银弹,而是工程实践的沉淀。分层架构提供职责分离的基础,MVVM 适合表单和交互密集的场景,状态驱动 UI 在复杂应用中提供清晰的数据流。选择架构模式时,优先考虑团队认知成本和项目复杂度,避免过度设计。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。