架構層 | 描述 |
M | 資料存取部分,由Django資料層處理 |
V | 選擇顯示哪些資料以及怎樣顯示的部分,由視圖和模闆處理 |
C | 根據使用者輸入委派視圖的部分,由Django架構根據URLconf設定,對給定URL調用适當的Python函數 |
| |
Model | 資料存取層,處理與資料相關的所有事務,即如何存取如何驗證有效 |
Template | 表現層,處理與表現相關的決定,即如何在頁面或者其他類型的文檔中進行顯示 |
View | 業務邏輯層,包含存取模型及調取恰當模闆的相關邏輯,可以看作是模型和模闆之間的橋梁 |
以往的開發模式
class ProductInfo:
def __init__(self):
self.product_name = None
self.id = None
self.price = None
self.manufacturer = None
from MTV.module_product import ProductInfo
class ProductView:
def print_product(self):
product = ProductInfo() # 執行個體化類,但也産生了耦合點
print(f"Name: {product.product_name}")
print(f"Price: {product.price}")
print(f"Manufacturer: {product.manufacturer}")
if __name__ == '__main__':
show_product = ProductView()
show_product.print_product()
将這個例子改為MVC模式
class ProductInfo:
"""
model
"""
def __init__(self):
self.product_name = None
self.id = None
self.price = None
self.manufacturer = None
class ProductView:
"""
view
"""
def print_product(self, product):
print(f"Name: {product.product_name}")
print(f"Price: {product.price}")
print(f"Manufacturer: {product.manufacturer}")
from MTV.view_product import ProductView
from MTV.model_product import ProductInfo
class ProductController:
"""
控制器
"""
def __init__(self, product, view):
self.product = product
self.product_view = view
def refresh_view(self):
"""
:return:
"""
self.product_view.print_product(self.product)
def update_model(self, product_name, price, manufacturer):
"""
更新對象屬性
:param product_name:
:param price:
:param manufacturer:
:return:
"""
self.product.product_name = product_name
self.product.price = price
self.product.manufacturer = manufacturer
if __name__ == '__main__':
controller = ProductController(ProductInfo(), ProductView())
controller.refresh_view()
controller.update_model("newname", 15, "davieyang")
controller.refresh_view()