【编程思想】【设计模式】【结构模式Structural】MVC
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的更多相关文章
- 【编程思想】【设计模式】【结构模式Structural】代理模式Proxy
Python版 https://github.com/faif/python-patterns/blob/master/structural/proxy.py #!/usr/bin/env pytho ...
- 【编程思想】【设计模式】【结构模式Structural】front_controller
Python版 https://github.com/faif/python-patterns/blob/master/structural/front_controller.py #!/usr/bi ...
- 【编程思想】【设计模式】【结构模式Structural】享元模式flyweight
Python版 https://github.com/faif/python-patterns/blob/master/structural/flyweight.py #!/usr/bin/env p ...
- 【编程思想】【设计模式】【结构模式Structural】门面模式/外观模式Facade
Python版 https://github.com/faif/python-patterns/blob/master/structural/facade.py #!/usr/bin/env pyth ...
- 【编程思想】【设计模式】【结构模式Structural】装饰模式decorator
Python版 https://github.com/faif/python-patterns/blob/master/structural/decorator.py #!/usr/bin/env p ...
- 【编程思想】【设计模式】【结构模式Structural】组合模式composite
Python版 https://github.com/faif/python-patterns/blob/master/structural/composite.py #!/usr/bin/env p ...
- 【编程思想】【设计模式】【结构模式Structural】桥梁模式/桥接模式bridge
Python版 https://github.com/faif/python-patterns/blob/master/structural/bridge.py #!/usr/bin/env pyth ...
- 【编程思想】【设计模式】【结构模式Structural】适配器模式adapter
Python版 https://github.com/faif/python-patterns/blob/master/structural/adapter.py #!/usr/bin/env pyt ...
- 【编程思想】【设计模式】【结构模式Structural】3-tier
Pyhon版 https://github.com/faif/python-patterns/blob/master/structural/3-tier.py #!/usr/bin/env pytho ...
随机推荐
- 常见的yaml写法-CronJob
CronJob其实就是在Job的基础上加上了时间调度,我们可以:在给定的时间点运行一个任务,也可以周期性地在给定时间点运行.这个实际上和我们Linux中的crontab就非常类似了.一个CronJob ...
- Java学习(九)
今天先学习了内联框架的知识,使用iframe的标签,还有超链接的知识. 做了个小实践 <!DOCTYPE html> <head> <meta charset=" ...
- 简单的SQl时间序列生成,每次时间间隔10分钟。
create table #timeseries(Times datetime not null) go declare @firstdate datetime , @lastdate datetim ...
- Spark 安装部署与快速上手
Spark 介绍 核心概念 Spark 是 UC Berkeley AMP lab 开发的一个集群计算的框架,类似于 Hadoop,但有很多的区别. 最大的优化是让计算任务的中间结果可以存储在内存中, ...
- 单元测试NUnit,mock组件NSubstitute,信号量SemaphoreSlim,异步lock等例子
public class LockTest { private IDatabase _database; private readonly Random _random = new Random(); ...
- 使用 kubeadm 部署
上一章中,我们用 minikube 去搭建单机集群,并且创建 Deployment.Service(在三章中讲解),本篇将介绍利用 kubeadm 部署多节点集群,并学会 安装以及使用 kuberne ...
- led汇编点灯
1. 汇编LED原理 为什么使用Cortex-A汇编 使用汇编初始化soc外设 使用汇编初始化DDR,I.MX不需要,因为它内部的96k ROM中存放了自己编写的启动代码,这些代码可以读取DDR配置信 ...
- 【性能优化】(2)JVM调优
JVM调优 2019-07-21 12:32:00 by冲冲 1.
- nginx安装与配置3-反向代理两台
1.nginx 反向代理 两台tomcat 2.8080.8081 启动tomcat 记住每个tomcat都有两个端口不要出现tomcat端口占用情况 3.启动项目访问,不报错可以访问 4.在每个to ...
- java的String参数格式化
String类的format()方法用于创建格式化的字符串以及连接多个字符串对象.熟悉C语言的同学应该记得C语言的sprintf()方法,两者有类似之处.format()方法有两种重载形式. form ...