【编程思想】【设计模式】【结构模式Structural】MVC
阅读原文时间:2023年07月08日阅读:2

Python版

https://github.com/faif/python-patterns/blob/master/structural/mvc.py

#!/usr/bin/env python

-*- coding: utf-8 -*-

"""
*TL;DR80
Separates data in GUIs from the ways it is presented, and accepted.
"""

class Model(object):

def \_\_iter\_\_(self):  
    raise NotImplementedError

def get(self, item):  
    """Returns an object with a .items() call method  
    that iterates over key,value pairs of its information."""  
    raise NotImplementedError

@property  
def item\_type(self):  
    raise NotImplementedError

class ProductModel(Model):

class Price(float):  
    """A polymorphic way to pass a float with a particular  
    \_\_str\_\_ functionality."""

    def \_\_str\_\_(self):  
        first\_digits\_str = str(round(self, 2))  
        try:  
            dot\_location = first\_digits\_str.index('.')  
        except ValueError:  
            return (first\_digits\_str + '.00')  
        else:  
            return (first\_digits\_str +  
                    '0' \* (3 + dot\_location - len(first\_digits\_str)))

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):  
    for item in self.products:  
        yield item

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(object):

def show\_item\_list(self, item\_type, item\_list):  
    raise NotImplementedError

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()"""  
    raise NotImplementedError

def item\_not\_found(self, item\_type, item\_name):  
    raise NotImplementedError

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('That %s "%s" does not exist in the records' %  
          (item\_type, item\_name))

class Controller(object):

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):  
    try:  
        item\_info = self.model.get(item\_name)  
    except:  
        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)

if __name__ == '__main__':

model = ProductModel()  
view = ConsoleView()  
controller = Controller(model, view)  
controller.show\_items()  
controller.show\_item\_information('cheese')  
controller.show\_item\_information('eggs')  
controller.show\_item\_information('milk')  
controller.show\_item\_information('arepas')

OUTPUT ###

PRODUCT LIST:

cheese

eggs

milk

PRODUCT INFORMATION:

Name: Cheese, Price: 2.00, Quantity: 10

PRODUCT INFORMATION:

Name: Eggs, Price: 0.20, Quantity: 100

PRODUCT INFORMATION:

Name: Milk, Price: 1.50, Quantity: 10

That product "arepas" does not exist in the records

Python转载版