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. 六问六答理解ForkJoin原理

    摘要:ForkJoin线程池是将任务分割为子任务,有可能子任务还是很大,还需要进一步拆解,最终得到足够小的任务. 本文分享自华为云社区<ForkJoin线程池的学习和思考>,作者:brea ...

  2. CommonJS与ES6 Module的使用与区别

    CommonJS与ES6 Module的使用与区别 1. CommonJS 1.1 导出 1.2 导入 2. ES6 Module 2.1 导出 2.2 导入 3. CommonJS 与 ES6 Mo ...

  3. SSH服务器拒绝了密码。请再试一次。怎么改都不行

    使用Xshell连接服务器,之前还好好的,突然之间就报"SSH服务器拒绝了密码.请再试一次"的错误. 1.检查 检查了IP.连接端口.用户.密码.网络是否正确? 本机情况:能够pi ...

  4. 自动下载MarkDown格式会议论文的程序

    近期师兄发给我一个压缩包让我整理文献,而我发现压缩包里的内容是这样: 这样: 和这样的: 我大概看了一下,可能有270多篇文章是这种格式,俗话说的好,没有困难的工作,只有勇敢的研究僧.所以决定用Pyt ...

  5. css--元素居中常用方法总结

    前言 元素居中是日常开发和学习中最常见的问题,同时也是面试中经常考察的知识点,本文来总结一下这方面的知识点. 正文 1.水平居中 (1)子父元素宽度固定,子元素设置 margin:auto,并且子元素 ...

  6. AsExpandable EF多条件查询

    我个人学习新技术有一个方法,如果遇到问题会根据以前的经验来寻找一些类似的解决方法.有人会说,如果这个问题在你的学习或者工作生涯中都没有遇到过呢?很简单,通过搜索资料或查阅相关书籍学习别人的经验. 在如 ...

  7. 『学了就忘』Linux软件包管理 — 43、RPM包的校验和证书

    目录 1.RPM包的校验 (1)RPM包校验基本命令 (2)校验某个系统文件是否被修改举例 (3)验证内容中8个信息的具体内容 (4)文件类型有哪些 2.RPM包的证书 (1)数字证书 (2)数字证书 ...

  8. 使用 docker + verdaccio 搭建npm私有仓库

    本文介绍如何使用 verdaccio 搭建私有npm仓库,以及使用 docker 时如何映射到本地目录,方便简单对仓库进行各种操作.系统环境是 Linux. verdaccio verdaccio 是 ...

  9. [luogu4259]寻找车位

    考虑一个分治的做法:按行分治,将所有区间分为两类--经过分割线的.在左/右区间内部,后者显然可以递归下取,考虑前者 先求出出该行上每一列向上和向下的最大长度,记作$up_{i}$和$down_{i}$ ...

  10. [bzoj1042]硬币购物

    先预处理出没有上限的方案数,然后容斥,然后将所有东西的范围都变为[0,+oo),即可用预处理出的dp数组计算 1 #include<bits/stdc++.h> 2 using names ...