Python设计模式——MVC模式(Model-View-Controller)

MVC模式(Model-View-Controller)

MVC模式的名称来自于切分软件应用的三个部分,即模型部分、视图部分和控制器部分。MVC被认为是一种架构设计而不是实际模式,但由于其非常重要,在介绍设计模式时无法绕过它。

一方面,MVC是一个非常古早的模式,当时的计算机硬件环境和当前有着较大的差别,尤其是View的概念和内涵也在发生变化。我们不需要机械地硬套MVC的结构,而是更多的理解其思想。
另一方面,基于MVC的许多变种,如MVVM,是当前更常见的架构设计。

返回 Python设计模式-outline

例子

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

关于iter:https://blog.csdn.net/LaoYuanPython/article/details/89609187?csdn_share_tail={"type"%3A"blog"%2C"rType"%3A"article"%2C"rId"%3A"89609187"%2C"source"%3A"qq_51352578"}&ctrtid=3flVi

关于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

posted @ 2022-07-26 17:47  坦先生的AI资料室  阅读(529)  评论(0编辑  收藏  举报