【编程思想】【设计模式】【结构模式Structural】MVC
2024-10-15 19:58:17
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转载版
最新文章
- 【FTP】FTP文件上传下载-支持断点续传
- TX Textcontrol 使用总结二——常见异常
- 【log4net】配置文件
- 代码自动生成工具_java版
- Spring boot 1.3.5 RELEASE 官方文档中文翻译--Part2:新手入门
- iOS Crash文件的解析
- android 7.0带来的
- linux下无ifconfig命令
- OVS VxLAN Flow 分析 - 每天5分钟玩转 OpenStack(149)
- SPI通讯协议
- GO开发[四]:golang函数
- 【Dojo 1.x】笔记3 等待DOM加载完成
- 2017 ACM Jordanian Collegiate Programming Contest
- 微信小程序开发笔记04
- spring boot报Unsupported Media Type Content type '*/*;charset=UTF-8' not supported
- oracle中order by造成分页错误
- 【转】SQL Server 运行状况监控SQL语句
- 1.3、CDH 搭建Hadoop在安装之前(端口)
- numpy.squeeze()的用法
- [SpringMVC] - 简单说明什么是SpringMVC
热门文章
- 找第k个结点 剑指22
- Mysql教程:(六)修改语句、、删除语句、字符查询like
- [JavaScript闭包]Javascript闭包的判别,作用和示例
- mongo笔记
- c++学习笔记目录
- CodeGuide 300+文档、100+代码库,一个指导程序员写代码的,Github 仓库开源啦!
- Windows漏洞:MS08-067远程代码执行漏洞复现及深度防御
- 分布式条件下Integer大小比值的问题
- Vue安装Vue Devtools调试工具提示 Error: Cannot find module '@vue-devtools/build-tools' 解决办法
- WinForm训练一_改变窗体大小