Python设计模式-三层架构模式(3-tier)

三层架构模式(3-tier)

三层架构指:

  • 表现层(presentation layer): 也称UI层,程序运行的入口,如果程序包括界面,界面就放在这一层。
  • 业务逻辑层(business logic layer):王城程序的业务逻辑,对数据访问层进行调用,将从数据访问层中获取的数据反馈给表现层
  • 数据层(data):直接操作数据库。

其目的是为了实现“高内聚低耦合”的状态。高内聚是指,一个模块有相关性很强的代码组成,且只负责一项任务,即单一责任原则。低耦合是指:模块之间尽量独立。

返回 Python设计模式-outline

示例

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")
posted @   坦先生的AI资料室  阅读(434)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示