> 文章列表 > MVC和MVVM模式的区别

MVC和MVVM模式的区别

MVC和MVVM模式的区别

MVVM 和 MVC 都是软件架构模式,其中 MVVM 表示“Model-View-ViewModel”,而 MVC 表示“Model-View-Controller”。

MVC 模式中,控制器(Controller)充当视图(View)和模型(Model)之间的中介,将用户输入从视图传递到模型并将模型状态更新反映回视图。这种方式有助于分离应用程序的不同部分,并促进代码重用和可维护性。

MVVM 模式也旨在实现分离视图和业务逻辑。在 MVVM 中,ViewModel 充当视图(View)和模型(Model)之间的中介,并向视图公开数据和命令(Command)。 ViewModel 通过数据绑定机制将其状态同步到视图上。这种方式有助于提高应用程序的可测试性以及使用数据绑定带来的生产力增益。

因此,MVVM 与 MVC 的区别在于

  1. 视图和模型之间的通信方式不同:在 MVC 中,视图直接与控制器通信,并通过控制器与模型交互;而在 MVVM 中,视图通过数据绑定与 ViewModel 通信,并由 ViewModel 与模型交互。

  2. MVVM 引入了 ViewModel 层:ViewModel 是一个介于视图和模型之间的中间层,负责处理视图显示和用户输入的逻辑。这个层的引入使得视图和模型之间的耦合度更低,也使得视图和业务逻辑的重用性更高。

  3. 数据绑定:MVVM 中的视图和 ViewModel 之间通过数据绑定实现双向通信,而在 MVC 中,视图和控制器之间只能通过事件监听和回调等方式进行单向通信。

下面是一个简单的 MVVM 和 MVC 的 demo:

MVVM:

// Model
class Person {constructor(firstName, lastName) {this.firstName = firstName;this.lastName = lastName;}
}// ViewModel
class PersonViewModel {constructor(person) {this.person = person;}get fullName() {return `${this.person.firstName} ${this.person.lastName}`;}set fullName(value) {const [firstName, lastName] = value.split(' ');this.person.firstName = firstName;this.person.lastName = lastName;}
}// View
const input = document.querySelector('input');
const output = document.querySelector('p');// Data binding
const person = new Person('John', 'Doe');
const viewModel = new PersonViewModel(person);
input.value = viewModel.fullName;
input.addEventListener('input', (event) => {viewModel.fullName = event.target.value;output.innerText = viewModel.fullName;
});

MVC:

// Model
class Person {constructor(firstName, lastName) {this.firstName = firstName;this.lastName = lastName;}
}// Controller
class PersonController {constructor(person, view) {this.person = person;this.view = view;}updateFullName(fullName) {const [firstName, lastName] = fullName.split(' ');this.person.firstName = firstName;this.person.lastName = lastName;this.updateView();}updateView() {this.view.update(this.person.firstName + ' ' + this.person.lastName);}
}// View
class PersonView {constructor(controller) {this.controller = controller;this.input = document.querySelector('input');this.output = document.querySelector('p');this.init();}init() {this.input.value = this.controller.person.firstName + ' ' + this.controller.person.lastName;this.input.addEventListener('input', (event) => {this.controller.updateFullName(event.target.value);});this.update(this.input.value);}update(value) {this.output.innerText = value;}
}// Create objects and start the app
const person = new Person('John', 'Doe');
const view = new PersonView(new PersonController(person, new PersonView()));

MVVM(Model-View-ViewModel)的好处如下:

  1. 分离关注点:MVVM 将用户界面(View)与业务逻辑(ViewModel)分离,使得代码维护更加容易,并且能够提高代码的可读性和可测试性。

  2. 易于扩展:由于 MVVM 模式中的每个组件都是独立的,因此您可以轻松地添加新功能或更改现有功能而不影响其他部分。

  3. 可重用性:MVVM 模式促进了代码重复使用,因为 ViewModel 可以轻松地在多个视图之间共享。

  4. 容易维护:MVVM 模式允许开发人员专注于业务逻辑和数据,而不必考虑视图的状态管理和同步问题。

  5. 支持异步和数据绑定:MVVM 模式通过双向数据绑定和命令来支持异步操作,这使得 UI 的更新变得更加容易和直观。