Khám Phá Mẫu Thiết Kế Python: Mô Hình-View-Controller (Phần 2)

Luận văn thạc sĩ phân tích Mastering python design patterns part 2, đánh giá thực trạng, chỉ ra hạn chế, đề xuất giải pháp khả thi cho thực tiễn.

Trường đại học

Trường Đại Học

Chuyên ngành

Khoa Học Máy Tính

Người đăng

Ẩn danh

Thể loại

bài viết

2023

107
1
0

Phí lưu trữ

35 Point

Mục lục chi tiết

1. CHƯƠNG 8: THE MODEL-VIEW-CONTROLLER PATTERN

8.1. One of the design principles related to software engineering is the Separation of Concerns (SoC) principle

8.2. The Model-View-Controller Pattern

8.3. A real-life example

8.4. A software example

8.5. Use cases

8.6. Implementation

8.7. Summary

9. CHƯƠNG 9: THE PROXY PATTERN

9.1. In some applications, we want to execute one or more important action before accessing an object

9.2. The Proxy Pattern

9.3. The LazyProperty class

9.4. The Test class example

9.5. Kinds of lazy initialization in OOP

9.6. A real-life example

Tóm tắt

I. Khám Phá Mô Hình View Controller Trong Python Tổng Quan

Mô hình-View-Controller (MVC) là một trong những mẫu thiết kế quan trọng trong lập trình phần mềm. Nó giúp tách biệt các phần của ứng dụng, từ đó dễ dàng quản lý và bảo trì. MVC áp dụng nguyên tắc phân tách mối quan tâm (Separation of Concerns - SoC), cho phép phát triển ứng dụng một cách hiệu quả hơn. Mô hình này bao gồm ba thành phần chính: mô hình, view và controller. Mỗi thành phần có vai trò riêng, giúp tối ưu hóa quy trình phát triển phần mềm.

1.1. Mô Hình MVC Trong Python Định Nghĩa và Vai Trò

Mô hình MVC trong Python giúp phân chia ứng dụng thành ba phần: mô hình (model), view và controller. Mô hình chứa logic và dữ liệu, view hiển thị thông tin, còn controller xử lý tương tác giữa người dùng và mô hình.

1.2. Lợi Ích Của Việc Sử Dụng Mô Hình MVC

Sử dụng mô hình MVC giúp tăng cường khả năng bảo trì và mở rộng ứng dụng. Các nhà phát triển có thể thay đổi view mà không ảnh hưởng đến mô hình, và ngược lại, giúp tiết kiệm thời gian và công sức.

II. Thách Thức Khi Áp Dụng Mô Hình MVC Trong Python

Mặc dù mô hình MVC mang lại nhiều lợi ích, nhưng việc áp dụng nó cũng gặp phải một số thách thức. Một trong những vấn đề chính là việc quản lý sự tương tác giữa các thành phần. Nếu không được thiết kế đúng cách, ứng dụng có thể trở nên phức tạp và khó bảo trì.

2.1. Quản Lý Tương Tác Giữa Các Thành Phần

Việc quản lý tương tác giữa mô hình, view và controller là rất quan trọng. Nếu controller không xử lý đúng cách, có thể dẫn đến lỗi trong việc hiển thị dữ liệu hoặc xử lý yêu cầu từ người dùng.

2.2. Khó Khăn Trong Việc Bảo Trì Ứng Dụng

Khi ứng dụng trở nên phức tạp, việc bảo trì có thể trở thành một thách thức lớn. Các nhà phát triển cần đảm bảo rằng mỗi thành phần được thiết kế rõ ràng và có trách nhiệm riêng biệt.

III. Phương Pháp Triển Khai Mô Hình MVC Trong Python

Để triển khai mô hình MVC trong Python, có thể sử dụng các framework như Django hoặc Flask. Những framework này cung cấp cấu trúc sẵn có cho việc phát triển ứng dụng, giúp tiết kiệm thời gian và công sức cho lập trình viên.

3.1. Sử Dụng Django Để Triển Khai MVC

Django là một framework mạnh mẽ cho việc phát triển ứng dụng web với mô hình MVC. Nó cung cấp các công cụ và thư viện cần thiết để xây dựng ứng dụng một cách nhanh chóng và hiệu quả.

3.2. Flask Framework Nhẹ Cho Mô Hình MVC

Flask là một framework nhẹ, dễ sử dụng cho việc phát triển ứng dụng web. Nó cho phép lập trình viên tùy chỉnh cấu trúc ứng dụng theo nhu cầu mà không bị ràng buộc bởi các quy tắc cứng nhắc.

IV. Ứng Dụng Thực Tiễn Của Mô Hình MVC Trong Python

Mô hình MVC được áp dụng rộng rãi trong nhiều ứng dụng thực tế. Từ các ứng dụng web đến các phần mềm quản lý, MVC giúp tổ chức mã nguồn một cách hiệu quả và dễ dàng bảo trì.

4.1. Ứng Dụng Web Sử Dụng MVC

Nhiều ứng dụng web hiện nay sử dụng mô hình MVC để tổ chức mã nguồn. Điều này giúp các nhà phát triển dễ dàng quản lý và mở rộng ứng dụng khi cần thiết.

4.2. Phát Triển Ứng Dụng Desktop Với MVC

Mô hình MVC cũng có thể được áp dụng trong phát triển ứng dụng desktop. Việc tách biệt các thành phần giúp cải thiện trải nghiệm người dùng và khả năng bảo trì ứng dụng.

V. Kết Luận Về Mô Hình View Controller Trong Python

Mô hình-View-Controller là một trong những mẫu thiết kế quan trọng trong lập trình phần mềm. Việc áp dụng mô hình này giúp tăng cường khả năng bảo trì và mở rộng ứng dụng. Các nhà phát triển nên nắm vững mô hình này để tối ưu hóa quy trình phát triển phần mềm.

5.1. Tương Lai Của Mô Hình MVC

Mô hình MVC sẽ tiếp tục đóng vai trò quan trọng trong phát triển phần mềm. Các framework mới sẽ tiếp tục cải tiến và tối ưu hóa mô hình này để đáp ứng nhu cầu ngày càng cao của người dùng.

5.2. Lời Khuyên Cho Lập Trình Viên

Lập trình viên nên tìm hiểu và áp dụng mô hình MVC trong các dự án của mình. Việc này không chỉ giúp cải thiện chất lượng mã nguồn mà còn nâng cao khả năng làm việc nhóm và bảo trì ứng dụng.

25/07/2025

Trích đoạn nội dung tài liệu

The Model-View-Controller Pattern One of the design principles related to software engineering is the Separation of Concerns (SoC) principle. The idea behind the SoC principle is to split an application into distinct sections, where each section addresses a separate concern. Examples of such concerns are the layers used in a layered design (data access layer, business logic layer, presentation layer, and so forth). Using the SoC principle simplifies the development and maintenance of software applications [j.

The Model-View-Controller (MVC) pattern is nothing more than the SoC principle applied to OOP. The name of the pattern comes from the three main components used to split a software application: the model, the view, and the controller. MVC is considered an architectural pattern rather than a design pattern. The difference between an architectural and a design pattern is that the former has a broader scope than the latter.

Nevertheless, MVC is too important to skip just for this reason. Even if we will never have to implement it from scratch, we need to be familiar with it because all common frameworks use MVC or a slightly different version of it (more on this later). The model is the core component. It represents knowledge.

It contains and manages the (business) logic, data, state, and rules of an application. The view is a visual representation of the model. Examples of views are a computer GUI, the text output of a computer terminal, a smartphone's application GUI, a PDF document, a pie chart, a bar chart, and so forth. The view only displays the data, it doesn't handle it.

The controller is the link/glue between the model and view. All communication between the model and the view happens through a controller [GOF95, page 14], [j. The Model-View-Controller Pattern A typical use of an application that uses MVC after the initial screen is rendered to the user is as follows: • The user triggers a view by clicking (typing, touching, and so on) a button • The view informs the controller about the user's action • The controller processes user input and interacts with the model • The model performs all the necessary validation and state changes, and informs the controller about what should be done • The controller instructs the view to update and display the output appropriately, following the instructions given by the model You might be wondering why is the controller part necessary? Can't we just skip it? We could, but then we would lose a big benefit that MVC provides: the ability to use more than one view (even at the same time, if that's what we want) without modifying the model. To achieve decoupling between the model and its representation, every view typically needs its own controller.

If the model communicated directly with a specific view, we wouldn't be able to use multiple views (or at least, not in a clean and modular way). A real-life example MVC is the SoC principle applied to OOP. The SoC principle is used a lot in real life. For example, if you build a new house, you usually assign different professionals to: • Install the plumbing and electricity • Paint the house Another example is a restaurant.

In a restaurant, the waiters receive orders and serve dishes to the customers, but the meals are cooked by the chefs [j. A software example The web2py web framework [j.mp/webtopy] is a lightweight Python framework that embraces the MVC pattern. If you have never tried web2py, I encourage you to do it since it is extremely simple to install. All I had to do was download a package and execute a single Python file (web2py.

There are many examples that demonstrate how MVC can be used in web2py on the project's web page [j.mp/web2pyex]. [ 94 ] Chapter 8 Django is also an MVC framework, although it uses different naming conventions. The controller is called view, and the view is called template. Django uses the name Model-Template-View (MTV).

According to the designers of Django, the view describes what data is seen by the user, and therefore, it uses the name view as the Python callback function for a particular URL. The term Template in Django is used to separate content from representation. It describes how the data is seen by the user, not which data is seen [j. Use cases MVC is a very generic and useful design pattern.

In fact, all popular Web frameworks (Django, Rails, and Yii) and application frameworks (iPhone SDK, Android, and QT) make use of MVC or a variation of it (Model-View-Adapter (MVA), Model-View-Presenter (MVP), and so forth). However, even if we don't use any of these frameworks, it makes sense to implement the pattern on our own because of the benefits it provides, which are as follows: • The separation between the view and model allows graphics designers to focus on the UI part and programmers to focus on development, without interfering with each other. • Because of the loose coupling between the view and model, each part can be modified/extended without affecting the other. For example, adding a new view is trivial.

Just implement a new controller for it. • Maintaining each part is easier because the responsibilities are clear. When implementing MVC from scratch, be sure that you create smart models, thin controllers, and dumb views [Zlobin13, page 9]. A model is considered smart because it: • Contains all the validation/business rules/logic • Handles the state of the application • Has access to application data (database, cloud, and so on) • Does not depend on the UI A controller is considered thin because it: • Updates the model when the user interacts with the view • Updates the view when the model changes • Processes the data before delivering it to the model/view, if necessary [ 95 ] The Model-View-Controller Pattern • Does not display the data • Does not access the application data directly • Does not contain validation/business rules/logic A view is considered dumb because it: • Displays the data • Allows the user to interact with it • Does only minimal processing, usually provided by a template language (for example, using simple variables and loop controls) • Does not store any data • Does not access the application data directly • Does not contain validation/business rules/logic If you are implementing MVC from scratch and want to find out if you did it right, you can try answering two key questions: • If your application has a GUI, is it skinnable? How easily can you change the skin/look and feel of it? Can you give the user the ability to change the skin of your application during runtime? If this is not simple, it means that something is going wrong with your MVC implementation [j.

• If your application has no GUI (for instance, if it's a terminal application), how hard is it to add GUI support? Or, if adding a GUI is irrelevant, is it easy to add views to display the results in a chart (pie chart, bar chart, and so on) or a document (PDF, spreadsheet, and so on)? If these changes are not trivial (a matter of creating a new controller with a view attached to it, without modifying the model), MVC is not implemented properly. If you make sure that these two conditions are satisfied, your application will be more flexible and maintainable compared to an application that does not use MVC. Implementation I could use any of the common frameworks to demonstrate how to use MVC but I feel that the picture will be incomplete. So I decided to show how to implement MVC from scratch, using a very simple example: a quote printer.

The idea is extremely simple. The user enters a number and sees the quote related to that number. The quotes are stored in a quotes tuple. This is the data that normally exists in a database, file, and so on, and only the model has direct access to it.

[ 96 ] Chapter 8 Let's consider the example in the following code: quotes = ('A man is not complete until he is married. Then he is finished.', 'As I said before, I never repeat myself.', 'Behind a successful man is an exhausted woman.', 'Black holes really suck.', 'Facts are stubborn things.') The model is minimalistic. It only has a get_quote() method that returns the quote (string) of the quotes tuple based on its index n. Note that n can be less than or equal to 0, due to the way indexing works in Python.

Improving this behavior is given as an exercise for you at the end of this section. class QuoteModel: def get_quote(self, n): try: value = quotes[n] except IndexError as err: value = 'Not found!' return value The view has three methods: show(), which is used to print a quote (or the message Not found!) on the screen, error(), which is used to print an error message on the screen, and select_quote(), which reads the user's selection. This can be seen in the following code: class QuoteTerminalView: def show(self, quote): print('And the quote is: "{}"'.format(quote)) def error(self, msg): print('Error: {}'.format(msg)) def select_quote(self): return input('Which quote number would you like to see? ') The controller does the coordination. The __init__() method initializes the model and view.

The run() method validates the quote index given by the user, gets the quote by the model, and passes it back to the view to be displayed as shown in the following code: class QuoteTerminalController: def __init__(self): self.model = QuoteModel() self.view = QuoteTerminalView() [ 97 ] The Model-View-Controller Pattern def run(self): valid_input = False while not valid_input: n = self.select_quote() try: n = int(n) except ValueError as err: self.error("Incorrect index '{}'".format(n)) else: valid_input = True quote = self.get_quote(n) self.show(quote) Last but not least, the main() function initializes and fires the controller as shown in the following code: def main(): controller = QuoteTerminalController() while True: controller.run() The following is the full code of the example (file mvc.py): quotes = ('A man is not complete until he is married. Then he is finished.', 'As I said before, I never repeat myself.', 'Behind a successful man is an exhausted woman.', 'Black holes really suck.', 'Facts are stubborn things.') class QuoteModel: def get_quote(self, n): try: value = quotes[n] except IndexError as err: value = 'Not found!' return value class QuoteTerminalView: def show(self, quote): print('And the quote is: "{}"'.format(quote)) def error(self, msg): print('Error: {}'.model = QuoteModel() self.view = QuoteTerminalView() def run(self): valid_input = False while not valid_input: try: n = self.select_quote() n = int(n) valid_input = True except ValueError as err: self.error("Incorrect index '{}'".format(n)) quote = self.get_quote(n) self.show(quote) def main(): controller = QuoteTerminalController() while True: controller.run() if __name__ == '__main__': main() A sample execution of mvc.py shows how the program handles errors and prints quotes to the user: >>> python3 mvc.py Which quote number would you like to see? a Error: Incorrect index 'a' Which quote number would you like to see? 40 And the quote is: "Not found!" Which quote number would you like to see? 0 And the quote is: "A man is not complete until he is married. Then he is finished." Which quote number would you like to see? 3 And the quote is: "Black holes really suck." [ 99 ] The Model-View-Controller Pattern Of course, you don't (and shouldn't) have to stop here. There are many interesting ideas that you can experiment with.

A few of them are: • Make the program more user-friendly by allowing only indexes of values greater than or equal to 1 to be given by the user. You will also need to modify get_quote(). • Add a graphical view using a GUI framework such as Tkinter, Pygame, or Kivy. How modular is the program? Can you decide during runtime which view will be used? • Give the user an option to view a random quote by typing a key, for example, key r.

• The index validation is currently done in the controller.

Nội dung được bảo vệ bản quyền — Tải xuống đầy đủ