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转载版

【编程思想】【设计模式】【结构模式Structural】MVC的更多相关文章

  1. 【编程思想】【设计模式】【结构模式Structural】代理模式Proxy

    Python版 https://github.com/faif/python-patterns/blob/master/structural/proxy.py #!/usr/bin/env pytho ...

  2. 【编程思想】【设计模式】【结构模式Structural】front_controller

    Python版 https://github.com/faif/python-patterns/blob/master/structural/front_controller.py #!/usr/bi ...

  3. 【编程思想】【设计模式】【结构模式Structural】享元模式flyweight

    Python版 https://github.com/faif/python-patterns/blob/master/structural/flyweight.py #!/usr/bin/env p ...

  4. 【编程思想】【设计模式】【结构模式Structural】门面模式/外观模式Facade

    Python版 https://github.com/faif/python-patterns/blob/master/structural/facade.py #!/usr/bin/env pyth ...

  5. 【编程思想】【设计模式】【结构模式Structural】装饰模式decorator

    Python版 https://github.com/faif/python-patterns/blob/master/structural/decorator.py #!/usr/bin/env p ...

  6. 【编程思想】【设计模式】【结构模式Structural】组合模式composite

    Python版 https://github.com/faif/python-patterns/blob/master/structural/composite.py #!/usr/bin/env p ...

  7. 【编程思想】【设计模式】【结构模式Structural】桥梁模式/桥接模式bridge

    Python版 https://github.com/faif/python-patterns/blob/master/structural/bridge.py #!/usr/bin/env pyth ...

  8. 【编程思想】【设计模式】【结构模式Structural】适配器模式adapter

    Python版 https://github.com/faif/python-patterns/blob/master/structural/adapter.py #!/usr/bin/env pyt ...

  9. 【编程思想】【设计模式】【结构模式Structural】3-tier

    Pyhon版 https://github.com/faif/python-patterns/blob/master/structural/3-tier.py #!/usr/bin/env pytho ...

随机推荐

  1. 【死磕 NIO】— Proactor模式是什么?很牛逼吗?

    大家好,我是大明哥. 上篇文章我们分析了高性能 IO模型Reactor模式,了解了什么是Reactor 模式以及它的三种常见的模式,这篇文章,大明再介绍另外一种高性能IO模型: Proactor. 为 ...

  2. IntelliJ IDEA 的 Bean validation 里有什么用

    IntelliJ IDEA  的 Bean validation 是指右侧的框. 平时都是缩起来的,今天心血来潮.研究下这个是干嘛的?怎么用. 三个按钮全按下的话,下面的项目就会有三个菜单可选项. C ...

  3. xpath解析案例

    xpath解析百度页面的百度一下 # 1)获取网页的源码 # 2)解析的服务器响应的文件 etree.HTML , 用来解析字符串格式的HTML文档对象,将传进去的字符串转变成 element 对象 ...

  4. php 递推 递归

    思想:如何利用数学模式,来解决对应的需求问题,然后利用代码实现对应的数据模型(逻辑) 算法:使用代码实现对应的数学模型,从而解决对应的业务问题 递推算法是一种简单的算法,级通过已知条件,利用特定关系得 ...

  5. 使用PAM模块实现普通用户之间su免密切换

    参考自:Allow user1 to "su - user2" without password https://unix.stackexchange.com/questions/ ...

  6. 题解 P6345 [CCO 2017]接雨滴

    解题思路 NOIP在即,感觉即将退役,或许是最后一篇题解了... 求水的体积不是特别好求,我们考虑求出 水+柱子 的体积最后再减去柱子的体积. 发现对于最高的柱子在中间的情况其实可以把最高柱子一侧的柱 ...

  7. Docker极简入门:使用Docker运行Java程序

    运行简单的Java程序 先在当前目录创建App.java文件 public class App{ public static void main(String[] args){ String os = ...

  8. idea插件 Background Image Plus 随机更换背景图片

    首先在市场搜索: Background Image Plus 设置图片: 在view中,有set 图片,有random图片,有clean图片的 设置就是用set,随便设置个路径. 重点来了,随机更换背 ...

  9. SpringBoot引入第三方jar的Bean的三种方式

    在SpringBoot的大环境下,基本上很少使用之前的xml配置Bean,主要是因为这种方式不好维护而且也不够方便. 因此本篇博文也不再介绍Spring中通过xml来声明bean的使用方式. 一.注解 ...

  10. ARC128D

    考虑我们直接\(dp\). 那么需要快速的求出一段是否可以被消掉只剩两端. 我们可以考虑反过来做的. 我们知道如果全为\(abab\)型或者\(aa\)型则无法消掉 那么我们要前缀和,以及遇到\(aa ...