Model‑View‑Controller, MVC (Схема "Модель-Вид-Контроллер")

MVC

Model-View-Controller (MVC, «Модель-представление-контроллер», «Модель-вид-контроллер») — схема разделения данных приложения и управляющей логики на три отдельных компонента: модель, представление и контроллер — таким образом, чтобы код был поддерживаемым, тестируемым и понятным.

Model-View-Controller (MVC, «Модель-Представление-Контроллер», «Модель-Вид-Контроллер») — схема разделения данных приложения и управляющей логики на три отдельных компонента: модель, представление и контроллер — таким образом, что модификация каждого компонента может осуществляться независимо

Был создан ряд модификаций концепции MVC (MVC, MVP, MVVM, MVI, HMVC), которые решают одну задачу — разделить ответственность в UI‑слое приложения

Шаблон MVC эволюционировал, породив такие варианты, как иерархический model–view–controller (HMVC), model–view–adapter (MVA), model–view–presenter (MVP), model–view–viewmodel (MVVM) и другие, которые адаптировали MVC к различным контекстам.

Близкие архитектурные альтернативы - Hexagonal architecture

MVC (Model‑View‑Controller)

MVP (Model‑View‑Presenter)

MVC vs MVP

MVVM (Model‑View‑ViewModel)

MVI (Model‑View‑Intent)

Упрощенный MC (Model‑Controller)

Упрощённый вариант MC (Model‑Controller) или относят к гибридным подходам, где логику обработки запросов (контроллер) и бизнес‑логику/доступ к данным (модель) объединяют в один слой. Как это выглядит на практике:

HMVC (Hierarchical model–view–controller)

Сравнительная таблица

КритерийMVCMVPMVVMMVI
Роль UI‑компонента Активен, может знать о Model Пассивен, только отображает и сообщает события Пассивен, синхронизируется через привязки Пассивен, отображает State
Поток данных Двунаправленный, не всегда явный Чёткий, через интерфейс View Через привязки (часто реактивно) Однонаправленный (Intent → State → View)
Тестируемость логики UI Средняя (контроллер может быть сложным) Высокая (Presenter легко тестировать) Высокая (ViewModel легко тестировать) Очень высокая (State и Reducer чистые функции)
Сложность внедрения Низкая Средняя Средняя/высокая (нужны привязки) Высокая
Типичные платформы Веб, CRUD Десктоп, Android (legacy) WPF, Xamarin, Android, iOS Мобильные, сложные фронтенды

Реализация MVC.

MVC. Текстовый редактор с вкладками на Python + PyQt

Архитектура MVC для редактора

СлойРольОписание
ModelДанные и бизнес-логика. Ничего не знает об интерфейсе. Хранит текст, название файла, путь, статус "изменено". Умеет открывать/сохранять файлы.
ViewИнтерфейс. Только показывает данные и ловит клики. QTabWidget (вкладки) + QTextEdit внутри каждой.
ControllerПосредник. Слушает события View, обновляет Model, обновляет View. Обрабатывает действия меню, переключение вкладок, закрытие файлов.

Модули: Модель; Контроллер; Представление; Точка входа; Тесты.

Модель (Model)
Разверните для просмотра
Модель (Model) — core/model.py
from dataclasses import dataclass from typing import Optional, List from pathlib import Path @dataclass class Document: """Представляет один открытый документ.""" file_path: Optional[str] = None content: str = "" is_modified: bool = False @property def title(self) -> str: """Возвращает заголовок для вкладки.""" if self.file_path: return Path(self.file_path).name return "Untitled" @property def full_title(self) -> str: """Возвращает полный заголовок с пометкой об изменениях.""" title = self.title if self.is_modified: return f"{title}*" return title class EditorModel: """Управляет всеми документами.""" def __init__(self): self._documents: List[Document] = [] self._current_index: int = -1 def new_document(self) -> int: """Создаёт новый пустой документ. Возвращает его индекс.""" doc = Document() self._documents.append(doc) self._current_index = len(self._documents) - 1 return self._current_index def open_document(self, file_path: str) -> int: """ Открывает файл и создаёт документ. Возвращает индекс созданного документа. """ try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() except Exception as e: raise IOError(f"Не удалось открыть файл: {e}") doc = Document(file_path=file_path, content=content, is_modified=False) self._documents.append(doc) self._current_index = len(self._documents) - 1 return self._current_index def save_document(self, index: int, file_path: Optional[str] = None) -> bool: """ Сохраняет документ. Если file_path указан, сохраняет как новый файл. Возвращает True в случае успеха. """ if index < 0 or index >= len(self._documents): return False doc = self._documents[index] save_path = file_path or doc.file_path if not save_path: return False try: with open(save_path, 'w', encoding='utf-8') as f: f.write(doc.content) doc.file_path = save_path doc.is_modified = False return True except Exception as e: raise IOError(f"Не удалось сохранить файл: {e}") def get_document(self, index: int) -> Optional[Document]: """Возвращает документ по индексу.""" if 0 <= index < len(self._documents): return self._documents[index] return None def get_all_documents(self) -> List[Document]: """Возвращает копию списка всех документов.""" return self._documents.copy() def close_document(self, index: int) -> bool: """ Закрывает (удаляет) документ по индексу. Контроллер перед вызовом должен проверить флаг is_modified и при необходимости подтвердить сохранение у пользователя. Возвращает True, если документ удалён. """ if index < 0 or index >= len(self._documents): return False self._documents.pop(index) if index < self._current_index: self._current_index -= 1 elif self._current_index >= len(self._documents): self._current_index = len(self._documents) - 1 return True def update_content(self, index: int, content: str) -> None: """Обновляет содержимое документа и помечает как изменённый.""" if 0 <= index < len(self._documents): doc = self._documents[index] doc.content = content doc.is_modified = True def get_current_index(self) -> int: """Возвращает индекс текущего документа.""" return self._current_index def set_current_index(self, index: int) -> None: """Устанавливает текущий индекс.""" if 0 <= index < len(self._documents): self._current_index = index def document_count(self) -> int: """Возвращает количество документов.""" return len(self._documents)
▴ Свернуть
Представление (View)
Разверните для просмотра
Представление (View) — core/view.py
from typing import Optional from PyQt5.QtWidgets import ( QMainWindow, QWidget, QVBoxLayout, QTabWidget, QTextEdit, QStatusBar, QMenuBar, QMenu, QAction, QFileDialog, QMessageBox, QApplication ) from PyQt5.QtCore import pyqtSignal, Qt from PyQt5.QtGui import QKeySequence class TextEditorWidget(QTextEdit): """Виджет для редактирования текста одного документа.""" def __init__(self, parent=None): super().__init__(parent) self.setFontPointSize(12) self.setTabChangesFocus(False) class MainWindow(QMainWindow): """Главное окно приложения.""" # Сигналы для контроллера file_new_triggered = pyqtSignal() file_open_triggered = pyqtSignal() file_save_triggered = pyqtSignal() file_save_as_triggered = pyqtSignal() tab_closed = pyqtSignal(int) tab_changed = pyqtSignal(int) content_changed = pyqtSignal(int, str) window_closed = pyqtSignal() def __init__(self): super().__init__() self._current_editor: Optional[TextEditorWidget] = None self._closing = False self.setWindowTitle("SimpleTextEditor") self.setGeometry(100, 100, 800, 600) # Центральный виджет central_widget = QWidget() self.setCentralWidget(central_widget) layout = QVBoxLayout(central_widget) layout.setContentsMargins(0, 0, 0, 0) # Вкладки self.tab_widget = QTabWidget() self.tab_widget.setTabsClosable(True) self.tab_widget.tabCloseRequested.connect(self._on_tab_close) self.tab_widget.currentChanged.connect(self._on_tab_changed) layout.addWidget(self.tab_widget) # Статусная строка self.status_bar = QStatusBar() self.setStatusBar(self.status_bar) self.status_bar.showMessage("Готов") self._create_menu() def _create_menu(self): """Создаёт меню и действия.""" menubar = self.menuBar() file_menu = menubar.addMenu("&File") new_action = QAction("&New", self) new_action.setShortcut(QKeySequence.New) new_action.triggered.connect(self.file_new_triggered.emit) file_menu.addAction(new_action) open_action = QAction("&Open", self) open_action.setShortcut(QKeySequence.Open) open_action.triggered.connect(self.file_open_triggered.emit) file_menu.addAction(open_action) file_menu.addSeparator() save_action = QAction("&Save", self) save_action.setShortcut(QKeySequence.Save) save_action.triggered.connect(self.file_save_triggered.emit) file_menu.addAction(save_action) save_as_action = QAction("Save &As", self) save_as_action.setShortcut(QKeySequence("Ctrl+Shift+S")) save_as_action.triggered.connect(self.file_save_as_triggered.emit) file_menu.addAction(save_as_action) file_menu.addSeparator() exit_action = QAction("E&xit", self) exit_action.setShortcut(QKeySequence.Quit) exit_action.triggered.connect(self.close) file_menu.addAction(exit_action) def _on_tab_close(self, index: int): """Обработчик закрытия вкладки.""" self.tab_closed.emit(index) def _on_tab_changed(self, index: int): """Обработчик смены вкладки.""" self.tab_changed.emit(index) self._update_current_editor() def _update_current_editor(self): """Обновляет ссылку на текущий редактор.""" current_widget = self.tab_widget.currentWidget() if isinstance(current_widget, TextEditorWidget): self._current_editor = current_widget def add_tab(self, title: str, content: str) -> int: """ Добавляет новую вкладку. Возвращает индекс созданной вкладки. """ editor = TextEditorWidget() editor.setPlainText(content) editor.textChanged.connect(self._on_editor_text_changed) index = self.tab_widget.addTab(editor, title) self.tab_widget.setCurrentIndex(index) self._update_current_editor() return index def update_tab_title(self, index: int, title: str): """Обновляет заголовок вкладки.""" self.tab_widget.setTabText(index, title) def get_editor(self, index: int) -> Optional[TextEditorWidget]: """Возвращает редактор по индексу вкладки.""" widget = self.tab_widget.widget(index) if isinstance(widget, TextEditorWidget): return widget return None def get_current_editor(self) -> Optional[TextEditorWidget]: """Возвращает текущий редактор.""" return self._current_editor def get_editor_content(self, index: int) -> str: """Возвращает содержимое редактора по индексу.""" editor = self.get_editor(index) if editor: return editor.toPlainText() return "" def set_editor_content(self, index: int, content: str): """Устанавливает содержимое редактора по индексу.""" editor = self.get_editor(index) if editor: editor.setPlainText(content) def close_tab(self, index: int): """Закрывает вкладку без подтверждения.""" self.tab_widget.removeTab(index) def get_current_index(self) -> int: """Возвращает индекс текущей вкладки.""" return self.tab_widget.currentIndex() def tab_count(self) -> int: """Возвращает количество вкладок.""" return self.tab_widget.count() def _on_editor_text_changed(self): """Обработчик изменения текста в редакторе.""" editor = self.sender() if isinstance(editor, TextEditorWidget): index = self.tab_widget.indexOf(editor) if index >= 0: self.content_changed.emit(index, editor.toPlainText()) def set_status(self, message: str, timeout: int = 5000): """Устанавливает сообщение в статусную строку.""" self.status_bar.showMessage(message, timeout) def update_status(self, file_path: Optional[str], is_modified: bool): """Обновляет постоянную информацию в статусной строке.""" if file_path: status = f"Файл: {file_path}" else: status = "Без имени" status += " | " + ("Изменено" if is_modified else "Сохранено") self.status_bar.showMessage(status) def show_error(self, message: str): """Показывает диалог с сообщением об ошибке.""" QMessageBox.critical(self, "Ошибка", message) def show_unsaved_dialog(self, title: str) -> str: """ Показывает диалог о несохранённых изменениях. Возвращает 'save', 'discard' или 'cancel'. """ reply = QMessageBox.question( self, "Несохранённые изменения", f"Сохранить изменения в «{title}» перед закрытием?", QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel ) if reply == QMessageBox.Save: return "save" if reply == QMessageBox.Discard: return "discard" return "cancel" def show_save_dialog(self) -> Optional[str]: """Показывает диалог сохранения файла.""" file_path, _ = QFileDialog.getSaveFileName( self, "Сохранить файл", "", "Text Files (*.txt);;All Files (*)" ) return file_path if file_path else None def show_open_dialog(self) -> Optional[str]: """Показывает диалог открытия файла.""" file_path, _ = QFileDialog.getOpenFileName( self, "Открыть файл", "", "Text Files (*.txt);;All Files (*)" ) return file_path if file_path else None def closeEvent(self, event): """Обработчик закрытия окна.""" if self._closing: event.accept() else: event.ignore() self.window_closed.emit() def force_close(self): """Принудительно закрывает окно (вызывается контроллером).""" self._closing = True self.close()
▴ Свернуть
Контроллер (Controller)
Разверните для просмотра
Контроллер (Controller) — core/controller.py
from typing import Optional from src.model import EditorModel from src.view import MainWindow class EditorController: """Координирует работу Model и View.""" def __init__(self, model: EditorModel, view: MainWindow): self.model = model self.view = view view.file_new_triggered.connect(self.create_new_tab) view.file_open_triggered.connect(self.open_file) view.file_save_triggered.connect(self.save_current_file) view.file_save_as_triggered.connect(self.save_current_file_as) view.tab_closed.connect(self.close_tab) view.tab_changed.connect(self.on_tab_changed) view.content_changed.connect(self.on_content_changed) view.window_closed.connect(self.on_window_closed) self.create_new_tab() def create_new_tab(self): """Создаёт новую вкладку с пустым документом.""" index = self.model.new_document() doc = self.model.get_document(index) if doc: self.view.add_tab(doc.full_title, doc.content) self.view.update_status(doc.file_path, doc.is_modified) self.view.set_status("Создан новый файл") def open_file(self, file_path: Optional[str] = None): """Открывает файл.""" if not file_path: file_path = self.view.show_open_dialog() if not file_path: return try: index = self.model.open_document(file_path) doc = self.model.get_document(index) if doc: self.view.add_tab(doc.full_title, doc.content) self.view.update_status(doc.file_path, doc.is_modified) self.view.set_status(f"Открыто: {file_path}") except Exception as e: self.view.show_error(str(e)) def save_document_at(self, index: int, file_path: Optional[str] = None): """Сохраняет документ по указанному индексу.""" doc = self.model.get_document(index) if not doc: return if not doc.file_path and not file_path: file_path = self.view.show_save_dialog() if not file_path and not doc.file_path: return try: self.model.save_document(index, file_path) self.view.update_tab_title(index, doc.full_title) self.view.update_status(doc.file_path, doc.is_modified) self.view.set_status(f"Сохранено: {doc.file_path or file_path}") except Exception as e: self.view.show_error(str(e)) def save_current_file(self, file_path: Optional[str] = None): """Сохраняет текущий файл.""" index = self.model.get_current_index() self.save_document_at(index, file_path) def save_current_file_as(self): """Сохраняет текущий файл под новым именем.""" file_path = self.view.show_save_dialog() if file_path: self.save_current_file(file_path) def close_tab(self, index: int): """Закрывает вкладку с подтверждением при необходимости.""" doc = self.model.get_document(index) if not doc: self.view.close_tab(index) return if doc.is_modified: result = self.view.show_unsaved_dialog(doc.title) if result == "save": self.save_document_at(index) if doc.is_modified: return elif result == "cancel": return editor = self.view.get_editor(index) if editor: try: editor.textChanged.disconnect() except TypeError: pass self.model.close_document(index) self.view.close_tab(index) current_idx = self.model.get_current_index() current_doc = self.model.get_document(current_idx) if current_doc: self.view.update_status( current_doc.file_path, current_doc.is_modified ) elif self.model.document_count() == 0: self.create_new_tab() def on_tab_changed(self, index: int): """Обработчик смены вкладки.""" self.model.set_current_index(index) doc = self.model.get_document(index) if doc: self.view.update_status(doc.file_path, doc.is_modified) def on_content_changed(self, index: int, content: str): """Обработчик изменения содержимого.""" self.model.update_content(index, content) doc = self.model.get_document(index) if doc: self.view.update_tab_title(index, doc.full_title) self.view.update_status(doc.file_path, doc.is_modified) def on_window_closed(self): """Обработчик закрытия окна.""" for i in range(self.model.document_count() - 1, -1, -1): doc = self.model.get_document(i) if doc and doc.is_modified: result = self.view.show_unsaved_dialog(doc.title) if result == "save": self.save_document_at(i) if doc.is_modified: return elif result == "cancel": return self.view.force_close()
▴ Свернуть
Точка входа — main.py
Разверните для просмотра
Точка входа — main.py
import sys from PyQt5.QtWidgets import QApplication from src.model import EditorModel from src.view import MainWindow from src.controller import EditorController def main(): app = QApplication(sys.argv) model = EditorModel() view = MainWindow() controller = EditorController(model, view) view.show() sys.exit(app.exec_()) if __name__ == "__main__": main()
▴ Свернуть
Тесты
Разверните для просмотра
Тесты — tests/test_model.py
import pytest from pathlib import Path from src.model import EditorModel, Document class TestEditorModel: """Тесты для EditorModel.""" def test_new_document(self): """TC-M-01: Создание нового документа.""" model = EditorModel() index = model.new_document() assert model.document_count() == 1 doc = model.get_document(index) assert doc is not None assert doc.content == "" assert doc.file_path is None assert doc.is_modified is False assert doc.title == "Untitled" assert doc.full_title == "Untitled" def test_open_document(self, tmp_path): """TC-M-02: Открытие файла.""" file_path = tmp_path / "test.txt" file_path.write_text("Hello World", encoding='utf-8') model = EditorModel() index = model.open_document(str(file_path)) assert model.document_count() == 1 doc = model.get_document(index) assert doc is not None assert doc.content == "Hello World" assert doc.file_path == str(file_path) assert doc.is_modified is False def test_open_document_not_found(self): """Открытие несуществующего файла.""" model = EditorModel() with pytest.raises(IOError): model.open_document("not_exists.txt") def test_save_document(self, tmp_path): """TC-M-03: Сохранение документа.""" model = EditorModel() index = model.new_document() doc = model.get_document(index) doc.content = "New content" doc.is_modified = True file_path = tmp_path / "save_test.txt" result = model.save_document(index, str(file_path)) assert result is True assert doc.file_path == str(file_path) assert doc.is_modified is False assert file_path.read_text(encoding='utf-8') == "New content" def test_save_document_without_path(self): """Сохранение документа без пути.""" model = EditorModel() index = model.new_document() result = model.save_document(index) assert result is False def test_close_modified_document(self): """Закрытие изменённого документа (принудительно).""" model = EditorModel() index = model.new_document() doc = model.get_document(index) doc.content = "Modified content" doc.is_modified = True assert model.close_document(index) is True assert model.document_count() == 0 def test_close_unmodified_document(self): """Закрытие документа без изменений.""" model = EditorModel() index = model.new_document() assert model.close_document(index) is True assert model.document_count() == 0 def test_close_document_wrong_index(self): """Закрытие документа с неверным индексом.""" model = EditorModel() assert model.close_document(0) is False assert model.close_document(-1) is False def test_update_content(self): """Обновление содержимого документа.""" model = EditorModel() index = model.new_document() model.update_content(index, "New text") doc = model.get_document(index) assert doc.content == "New text" assert doc.is_modified is True def test_multiple_documents(self): """Работа с несколькими документами.""" model = EditorModel() index1 = model.new_document() index2 = model.new_document() assert model.document_count() == 2 doc1 = model.get_document(index1) doc2 = model.get_document(index2) assert doc1 is not doc2 def test_document_title(self): """Проверка заголовка документа.""" doc = Document() assert doc.title == "Untitled" doc.file_path = "/home/user/test.txt" assert doc.title == "test.txt" doc.is_modified = True assert doc.full_title == "test.txt*" def test_close_document_updates_current_index(self): """Проверка корректировки текущего индекса при закрытии.""" model = EditorModel() idx_a = model.new_document() idx_b = model.new_document() idx_c = model.new_document() model.set_current_index(2) model.close_document(2) assert model.get_current_index() == 1 model.close_document(0) assert model.get_current_index() == 0 def test_close_middle_document_updates_current_index(self): """Закрытие документа ДО текущего должно сдвинуть индекс.""" model = EditorModel() model.new_document() model.new_document() model.new_document() model.set_current_index(2) model.close_document(0) assert model.get_current_index() == 1
Тесты — tests/test_controller.py
import pytest from pathlib import Path from src.model import EditorModel from src.view import MainWindow from src.controller import EditorController class TestEditorController: """Тесты для EditorController.""" def test_controller_initialization(self, qtbot): """Инициализация контроллера.""" view = MainWindow() model = EditorModel() controller = EditorController(model, view) assert controller is not None assert view.tab_count() == 1 assert model.document_count() == 1 def test_controller_create_new_tab(self, qtbot): """Создание новой вкладки через контроллер.""" view = MainWindow() model = EditorModel() controller = EditorController(model, view) initial_count = view.tab_count() controller.create_new_tab() assert view.tab_count() == initial_count + 1 assert model.document_count() == initial_count + 1 def test_controller_open_file(self, qtbot, tmp_path): """TC-C-01: Открытие файла через контроллер.""" file_path = tmp_path / "test.txt" file_path.write_text("Controller test", encoding='utf-8') view = MainWindow() model = EditorModel() controller = EditorController(model, view) initial_count = view.tab_count() controller.open_file(str(file_path)) assert view.tab_count() == initial_count + 1 assert "test.txt" in view.tab_widget.tabText(view.tab_count() - 1) editor = view.get_current_editor() assert editor is not None assert editor.toPlainText() == "Controller test" def test_controller_save(self, qtbot, tmp_path): """TC-C-02: Сохранение через контроллер.""" view = MainWindow() model = EditorModel() controller = EditorController(model, view) controller.create_new_tab() editor = view.get_current_editor() editor.setPlainText("New text") file_path = tmp_path / "save_test.txt" controller.save_current_file(str(file_path)) assert file_path.read_text(encoding='utf-8') == "New text" current_index = view.get_current_index() tab_title = view.tab_widget.tabText(current_index) assert "save_test" in tab_title assert "*" not in tab_title def test_controller_close_unmodified_tab(self, qtbot): """Закрытие неизменённой вкладки.""" view = MainWindow() model = EditorModel() controller = EditorController(model, view) controller.create_new_tab() index = view.get_current_index() controller.close_tab(index) assert view.tab_count() >= 1 def test_controller_close_modified_tab_discard(self, qtbot, monkeypatch): """Закрытие изменённой вкладки с потерей изменений.""" view = MainWindow() model = EditorModel() controller = EditorController(model, view) controller.create_new_tab() editor = view.get_current_editor() editor.setPlainText("Modified text") monkeypatch.setattr(view, 'show_unsaved_dialog', lambda title: "discard") index = view.get_current_index() controller.close_tab(index) assert view.tab_count() >= 1 def test_controller_tab_changed(self, qtbot): """Смена вкладки.""" view = MainWindow() model = EditorModel() controller = EditorController(model, view) controller.create_new_tab() controller.create_new_tab() view.tab_widget.setCurrentIndex(0) assert model.get_current_index() == 0 def test_controller_status_update(self, qtbot, tmp_path): """Обновление статусной строки.""" view = MainWindow() model = EditorModel() controller = EditorController(model, view) file_path = tmp_path / "test.txt" file_path.write_text("Test", encoding='utf-8') controller.open_file(str(file_path)) status = view.status_bar.currentMessage() assert "test.txt" in status assert "Открыто" in status def test_controller_close_tab_with_save(self, qtbot, tmp_path, monkeypatch): """Закрытие изменённой вкладки с сохранением.""" view = MainWindow() model = EditorModel() controller = EditorController(model, view) controller.create_new_tab() editor = view.get_current_editor() editor.setPlainText("Text to save") file_path = tmp_path / "close_save.txt" monkeypatch.setattr(view, 'show_unsaved_dialog', lambda title: "save") monkeypatch.setattr(view, 'show_save_dialog', lambda: str(file_path)) index = view.get_current_index() controller.close_tab(index) assert file_path.read_text(encoding='utf-8') == "Text to save"
▴ Свернуть
ТЕХНИЧЕСКОЕ ЗАДАНИЕ
Разверните для просмотра
Спецификация
ТЕХНИЧЕСКОЕ ЗАДАНИЕ Основной язык проекта - русский. 1. Общее описание SimpleTextEditor — минимальный текстовый редактор с поддержкой вкладок и базовых файловых операций на Python + PyQt5. Проект демонстрирует архитектуру MVC (Model-View-Controller). 1.1 Цели проекта Демонстрация MVC архитектуры в GUI-приложении Разделение ответственности между компонентами Тестируемость бизнес-логики Минимальный функционал для понимания принципов 1.2 Функциональные требования FR-1: Управление файлами FR-1.1 Открытие текстового файла через диалог выбора FR-1.2 Сохранение текущего файла FR-1.3 Сохранение файла под новым именем (Save As) FR-1.4 Создание нового пустого файла FR-2: Управление вкладками FR-2.1 Отображение каждого открытого файла в отдельной вкладке FR-2.2 Название вкладки = имя файла или "Untitled" для новых FR-2.3 Закрытие вкладки с подтверждением при наличии несохраненных изменений FR-2.4 Переключение между вкладками FR-3: Редактирование текста FR-3.1 Отображение и редактирование текста FR-3.2 Отслеживание изменений (флаг модификации) FR-3.3 Визуальное обозначение несохраненных изменений (* в заголовке) FR-4: Статусная строка FR-4.1 Отображение пути к текущему файлу FR-4.2 Отображение статуса "Сохранено"/"Изменено" 2. Архитектура MVC 2.1 Компоненты ┌─────────────────────────────────────────────────────────────┐ │ VIEW (View) │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ MainWindow (QMainWindow) │ │ │ │ - Menu Bar: File (New, Open, Save, Save As) │ │ │ │ - Tab Widget (QTabWidget) │ │ │ │ - Status Bar (QStatusBar) │ │ │ │ - Central Widget: QTabWidget │ │ │ └──────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ │ │ Сигналы/События ▼ ┌─────────────────────────────────────────────────────────────┐ │ CONTROLLER │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ EditorController │ │ │ │ - Обрабатывает действия пользователя │ │ │ │ - Координирует Model и View │ │ │ │ - Содержит ссылки на Model и View │ │ │ └──────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ │ │ Запросы/Обновления ▼ ┌─────────────────────────────────────────────────────────────┐ │ MODEL │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ EditorModel │ │ │ │ - Управляет списком документов │ │ │ │ - Загрузка/сохранение файлов │ │ │ │ - Отслеживание изменений │ │ │ └──────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ 2.2 Описание классов Document (Модель данных) class Document: """Представляет один открытый документ.""" Attributes: file_path: Optional[str] # Путь к файлу или None content: str # Текст документа is_modified: bool # Флаг изменений EditorModel (Модель) class EditorModel: """Управляет всеми документами и файловыми операциями.""" Methods: new_document() -> int # Создает новый документ open_document(file_path: str) -> int # Открывает файл save_document(index: int) -> bool # Сохраняет документ save_document_as(index: int, file_path: str) # Сохраняет как get_document(index: int) -> Document # Возвращает документ close_document(index: int) -> bool # Закрывает документ get_all_documents() -> List[Document] # Все документы MainWindow (View) class MainWindow(QMainWindow): """Главное окно приложения.""" Signals: file_new_triggered() file_open_triggered() file_save_triggered() file_save_as_triggered() tab_closed(index: int) tab_changed(index: int) content_changed(index: int, content: str) EditorController (Controller) class EditorController: """Координирует Model и View.""" Methods: create_new_tab() # Создает новую вкладку open_file() # Открывает файл save_current_file() # Сохраняет текущий файл save_current_file_as() # Сохраняет как close_tab(index: int) # Закрывает вкладку on_tab_changed(index: int) # Обработка смены вкладки on_content_changed(index: int, content: str) # Обработка изменений 3. Технические требования 3.1 Зависимости Python 3.8+ PyQt5 >= 5.15.0 pytest >= 7.0.0 (для тестов) pytest-qt >= 4.0.0 (для тестов GUI) 3.2 Структура проекта simple-text-editor/ ├── src/ │ ├── __init__.py │ ├── model.py # EditorModel, Document │ ├── view.py # MainWindow │ ├── controller.py # EditorController │ └── main.py # Точка входа ├── tests/ │ ├── __init__.py │ ├── test_model.py # Тесты модели │ └── test_controller.py # Тесты контроллера ├── requirements.txt └── README.md 4. Тест-кейсы 4.1 Тесты модели (test_model.py) TC-M-01: Создание нового документа def test_new_document(): model = EditorModel() index = model.new_document() doc = model.get_document(index) assert doc.content == "" assert doc.file_path is None assert doc.is_modified is False TC-M-02: Открытие файла def test_open_document(tmp_path): # Создаем тестовый файл file_path = tmp_path / "test.txt" file_path.write_text("Hello World", encoding='utf-8') model = EditorModel() index = model.open_document(str(file_path)) doc = model.get_document(index) assert doc.content == "Hello World" assert doc.file_path == str(file_path) assert doc.is_modified is False TC-M-03: Сохранение документа def test_save_document(tmp_path): model = EditorModel() index = model.new_document() doc = model.get_document(index) doc.content = "New content" doc.is_modified = True file_path = tmp_path / "save_test.txt" result = model.save_document(index, str(file_path)) assert result is True assert doc.file_path == str(file_path) assert doc.is_modified is False assert file_path.read_text(encoding='utf-8') == "New content" TC-M-04: Закрытие документа с изменениями def test_close_modified_document(): model = EditorModel() index = model.new_document() doc = model.get_document(index) doc.content = "Modified content" doc.is_modified = True # Должен вернуть True (требуется подтверждение) assert model.close_document(index) is True 4.2 Тесты контроллера (test_controller.py) TC-C-01: Открытие файла через контроллер def test_controller_open_file(qtbot, tmp_path): file_path = tmp_path / "test.txt" file_path.write_text("Controller test", encoding='utf-8') view = MainWindow() model = EditorModel() controller = EditorController(model, view) # Имитация выбора файла controller.open_file(str(file_path)) assert view.tab_widget.count() == 1 assert "test.txt" in view.tab_widget.tabText(0) TC-C-02: Сохранение изменений def test_controller_save(qtbot, tmp_path): view = MainWindow() model = EditorModel() controller = EditorController(model, view) # Создаем новый документ controller.create_new_tab() editor = view.get_current_editor() editor.setPlainText("New text") # Сохраняем file_path = tmp_path / "save_test.txt" controller.save_current_file(str(file_path)) assert file_path.read_text(encoding='utf-8') == "New text" 5. Интерфейс пользователя 5.1 Главное окно ┌──────────────────────────────────────────────────────────────┐ │ SimpleTextEditor - [*]untitled.txt │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ File Edit View Help │ │ │ │ ┌─────────────────────────────────────────────────┐ │ │ │ │ │ New Ctrl+N │ │ │ │ │ │ Open Ctrl+O │ │ │ │ │ │ Save Ctrl+S │ │ │ │ │ │ Save As Ctrl+Shift+S │ │ │ │ │ │ ────────────────────────────────────────────── │ │ │ │ │ │ Exit Ctrl+Q │ │ │ │ │ └─────────────────────────────────────────────────┘ │ │ │ └──────────────────────────────────────────────────────┘ │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ [tab1] [tab2] [tab3] │ │ │ │ ┌──────────────────────────────────────────────┐ │ │ │ │ │ │ │ │ │ │ │ Текст документа │ │ │ │ │ │ │ │ │ │ │ └──────────────────────────────────────────────┘ │ │ │ └──────────────────────────────────────────────────────┘ │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ File: /path/to/file.txt | Status: Saved │ │ │ └──────────────────────────────────────────────────────┘ │ └──────────────────────────────────────────────────────────────┘ 5.2 Горячие клавиши Действие Горячая клавиша Новый файл Ctrl+N Открыть файл Ctrl+O Сохранить Ctrl+S Сохранить как Ctrl+Shift+S Выйти Ctrl+Q 6. Принятые решения Минимализм — только базовый функционал для понимания MVC Разделение ответственности: Model — данные и бизнес-логика View — отображение и пользовательский интерфейс Controller — связь между Model и View Тестируемость — Model и Controller тестируются независимо от GUI Расширяемость — легко добавить новые функции через Controller
▴ Свернуть
Диаграмма классов
Разверните для просмотра
classes
▴ Свернуть
Итог

Как это работает

Преимущества:

СитуацияБез MVC (все в одном классе)С MVC
Баг при сохраненииИщете ошибку в 500 строках GUI-кода, где перемешаны QFileDialog, кодировки и стили кнопок.Смотрите только в TextDocument.save_to_file() — 10 строк чистой логики.
Хотите добавить автодополнение кодаДобавляете еще 200 строк в тот же класс.Пишете новую Модель (CodeDocument), которая наследуется от TextDocument, и подключаете через Контроллер. View не трогаете.
Хотите перейти с PyQt на TkinterПереписываете ВСЕ приложение.Переписываете только View (интерфейс). Модель и Контроллер остаются (если Controller не использует Qt-специфичные диалоги, а они у нас вынесены в View).
Юнит-тестыНевозможно тестировать логику без запуска окна.Пишете test_text_model.py, создаете doc = TextDocument(), тестируете сохранение без GUI.