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. 🏆【Alibaba中间件技术系列】「RocketMQ技术专题」帮你梳理RocketMQ或Kafka的选择理由以及二者PK

    前提背景 大家都知道,市面上有许多开源的MQ,例如,RocketMQ.Kafka.RabbitMQ等等,现在Pulsar也开始发光,今天我们谈谈笔者最常用的RocketMQ和Kafka,想必大家早就知 ...

  2. C# 计算农历日期方法(2021版)

    解决问题 旧版农历获取方法报错,会有 到 2021年 m数组越界了 if (LunarData[m] < 4095) 此方法可以解决 主体代码 public static class China ...

  3. 力扣 - 剑指 Offer 12. 矩阵中的路径

    题目 剑指 Offer 12. 矩阵中的路径 思路1(回溯.DFS) 这题可以使用回溯+递归来解决,思路如下: 将二维数组的每一个元素都作为起点进行回溯查找 每次查找的时候,都有四个方向,但是上一个方 ...

  4. Maven 依赖调解源码解析(六):dependencyManagement 版本锁定

    本文是系列文章<Maven 源码解析:依赖调解是如何实现的?>第六篇,主要介绍 dependencyManagement 版本锁定原则.请按顺序阅读其他系列文章,系列文章总目录参见:htt ...

  5. [loj3043]线段树

    考虑把每一个区间单独统计,令$f[i]$表示第i个区间有标记的次数,$g[i]$表示第i个区间及其祖先中存在标记的次数,然后对于操作将所有区间分为5类(T为已执行操作个数): 1.被修改,那么$f[i ...

  6. mysql密码忘记如何恢复(windows/liunx版本:mysql-8.0.27)

    windows/liunx版本:mysql-8.0.27参考官网文档: https://dev.mysql.com/doc/refman/8.0/en/resetting-permissions.ht ...

  7. 32、最长有效括号 | 算法(leetode,附思维导图 + 全部解法)300题

    零 标题:算法(leetode,附思维导图 + 全部解法)300题之(32)最长有效括号 一 题目描述 二 解法总览(思维导图) 三 全部解法 1 方案1 1)代码: // 方案1 "滑动窗 ...

  8. 常用的分布式ID生成器

    为何需要分布式ID生成器 **本人博客网站 **IT小神 www.itxiaoshen.com **拿我们系统常用Mysql数据库来说,在之前的单体架构基本是单库结构,每个业务表的ID一般从1增,通过 ...

  9. Yarp 让系统内调度更灵活

    简介 Yarp 是微软团队开发的一个反向代理组件, 除了常规的 http 和 https 转换通讯,它最大的特点是可定制化,很容易根据特定场景开发出需要的定制代理通道. 详细介绍:https://de ...

  10. 洛谷 P4755 - Beautiful Pair(主席树+分治+启发式优化)

    题面传送门 wssb,我紫菜 看到这类与最大值统计有关的问题可以很自然地想到分治,考虑对 \([l,r]\) 进行分治,求出对于所有 \(l\le x\le y\le r\) 的点对 \((x,y)\ ...