Python设计模式——MVC模式(Model-View-Controller)
MVC模式(Model-View-Controller)
MVC模式的名称来自于切分软件应用的三个部分,即模型部分、视图部分和控制器部分。MVC被认为是一种架构设计而不是实际模式,但由于其非常重要,在介绍设计模式时无法绕过它。
一方面,MVC是一个非常古早的模式,当时的计算机硬件环境和当前有着较大的差别,尤其是View的概念和内涵也在发生变化。我们不需要机械地硬套MVC的结构,而是更多的理解其思想。
另一方面,基于MVC的许多变种,如MVVM,是当前更常见的架构设计。
例子
from abc import ABC, abstractmethod
class Model(ABC):
@abstractmethod
def __iter__(self):
pass
@abstractmethod
def get(self, item):
"""Returns an object with a .items() call method
that iterates over key,value pairs of its information."""
pass
@property
@abstractmethod
def item_type(self):
pass
class ProductModel(Model):
class Price(float):
"""A polymorphic way to pass a float with a particular
__str__ functionality."""
def __str__(self):
return f"{self:.2f}"
products = {
"milk": {"price": Price(1.50), "quantity": 10},
"eggs": {"price": Price(0.20), "quantity": 100},
"cheese": {"price": Price(2.00), "quantity": 10},
}
item_type = "product"
def __iter__(self):
yield from self.products
def get(self, product):
try:
return self.products[product]
except KeyError as e:
raise KeyError(str(e) + " not in the model's item list.")
class View(ABC):
@abstractmethod
def show_item_list(self, item_type, item_list):
pass
@abstractmethod
def show_item_information(self, item_type, item_name, item_info):
"""Will look for item information by iterating over key,value pairs
yielded by item_info.items()"""
pass
@abstractmethod
def item_not_found(self, item_type, item_name):
pass
class ConsoleView(View):
def show_item_list(self, item_type, item_list):
print(item_type.upper() + " LIST:")
for item in item_list:
print(item)
print("")
@staticmethod
def capitalizer(string):
return string[0].upper() + string[1:].lower()
def show_item_information(self, item_type, item_name, item_info):
print(item_type.upper() + " INFORMATION:")
printout = "Name: %s" % item_name
for key, value in item_info.items():
printout += ", " + self.capitalizer(str(key)) + ": " + str(value)
printout += "\n"
print(printout)
def item_not_found(self, item_type, item_name):
print(f'That {item_type} "{item_name}" does not exist in the records')
class Controller:
def __init__(self, model, view):
self.model = model
self.view = view
def show_items(self):
items = list(self.model)
item_type = self.model.item_type
self.view.show_item_list(item_type, items)
def show_item_information(self, item_name):
"""
Show information about a {item_type} item.
:param str item_name: the name of the {item_type} item to show information about
"""
try:
item_info = self.model.get(item_name)
except Exception:
item_type = self.model.item_type
self.view.item_not_found(item_type, item_name)
else:
item_type = self.model.item_type
self.view.show_item_information(item_type, item_name, item_info)
REF
https://www.cnblogs.com/winter-cn/p/4285171.html
关于MVC和3tier的异同:https://blog.csdn.net/weixin_43232955/article/details/104963392?utm_medium=distribute.pc_relevant.none-task-blog-2defaultbaidujs_title~default-0-104963392-blog-113576985.pc_relevant_aa&spm=1001.2101.3001.4242.1&utm_relevant_index=3
本文来自博客园,作者:坦先生的AI资料室,转载请注明原文链接:https://www.cnblogs.com/yushengchn/p/16521945.html
分类:
python设计模式系列
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现