Python设计模式-三层架构模式(3-tier)
三层架构模式(3-tier)
三层架构指:
- 表现层(presentation layer): 也称UI层,程序运行的入口,如果程序包括界面,界面就放在这一层。
- 业务逻辑层(business logic layer):王城程序的业务逻辑,对数据访问层进行调用,将从数据访问层中获取的数据反馈给表现层
- 数据层(data):直接操作数据库。
其目的是为了实现“高内聚低耦合”的状态。高内聚是指,一个模块有相关性很强的代码组成,且只负责一项任务,即单一责任原则。低耦合是指:模块之间尽量独立。
示例
class Data:
"""Data Store Class"""
products = {
"milk": {"price": 1.50, "quantity": 10},
"eggs": {"price": 0.20, "quantity": 100},
"cheese": {"price": 2.00, "quantity": 10},
}
def __get__(self, obj, klas):
print("(Fetching from Data Store)")
return {"products": self.products}
class BusinessLogic:
"""Business logic holding data store instances"""
data = Data()
def product_list(self) -> KeysView[str]:
return self.data["products"].keys()
def product_information(
self, product: str
) -> Optional[Dict[str, Union[int, float]]]:
return self.data["products"].get(product, None)
class Ui:
"""UI interaction class"""
def __init__(self) -> None:
self.business_logic = BusinessLogic()
def get_product_list(self) -> None:
print("PRODUCT LIST:")
for product in self.business_logic.product_list():
print(product)
print("")
def get_product_information(self, product: str) -> None:
product_info = self.business_logic.product_information(product)
if product_info:
print("PRODUCT INFORMATION:")
print(
f"Name: {product.title()}, "
+ f"Price: {product_info.get('price', 0):.2f}, "
+ f"Quantity: {product_info.get('quantity', 0):}"
)
else:
print(f"That product '{product}' does not exist in the records")
if __name__ == '__main__':
ui = Ui()
ui.get_product_list()
ui.get_product_information("cheese")
本文来自博客园,作者:坦先生的AI资料室,转载请注明原文链接:https://www.cnblogs.com/yushengchn/p/16521909.html
分类:
python设计模式系列
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)