工厂模式

import xml.etree.ElementTree as etree
import json class JSONConnector: def __init__(self, filepath):
self.data = dict()
with open(filepath, mode='r', encoding='utf-8') as f:
self.data = json.load(f) @property
def parsed_data(self):
return self.data class XMLConnector: def __init__(self, filepath):
self.tree = etree.parse(filepath) @property
def parsed_data(self):
return self.tree def connection_factory(filepath):
if filepath.endswith('json'):
connector = JSONConnector
elif filepath.endswith('xml'):
connector = XMLConnector
else:
raise ValueError('Cannot connect to {}'.format(filepath))
return connector(filepath) def connect_to(filepath):
factory = None
try:
factory = connection_factory(filepath)
except ValueError as ve:
print(ve)
return factory def main():
sqlite_factory = connect_to('data/person.sq3')
print() xml_factory = connect_to('data/person.xml')
xml_data = xml_factory.parsed_data
liars = xml_data.findall(".//{}[{}='{}']".format('person',
'lastName', 'Liar'))
print('found: {} persons'.format(len(liars)))
for liar in liars:
print('first name: {}'.format(liar.find('firstName').text))
print('last name: {}'.format(liar.find('lastName').text))
[print('phone number ({})'.format(p.attrib['type']),
p.text) for p in liar.find('phoneNumbers')] print() json_factory = connect_to('data/donut.json')
json_data = json_factory.parsed_data
print('found: {} donuts'.format(len(json_data)))
for donut in json_data:
print('name: {}'.format(donut['name']))
print('price: ${}'.format(donut['ppu']))
[print('topping: {} {}'.format(t['id'], t['type'])) for t in donut['topping']] if __name__ == '__main__':
main()

抽象工厂

import random

class PetShop:

    """A pet shop"""

    def __init__(self, animal_factory=None):
"""pet_factory is our abstract factory. We can set it at will.""" self.pet_factory = animal_factory def show_pet(self):
"""Creates and shows a pet using the abstract factory""" pet = self.pet_factory.get_pet()
print("We have a lovely {}".format(pet))
print("It says {}".format(pet.speak()))
print("We also have {}".format(self.pet_factory.get_food())) # Stuff that our factory makes class Dog: def speak(self):
return "woof" def __str__(self):
return "Dog" class Cat: def speak(self):
return "meow" def __str__(self):
return "Cat" # Factory classes class DogFactory: def get_pet(self):
return Dog() def get_food(self):
return "dog food" class CatFactory: def get_pet(self):
return Cat() def get_food(self):
return "cat food" # Create the proper family
def get_factory():
"""Let's be dynamic!"""
return random.choice([DogFactory, CatFactory])() # Show pets with various factories for i in range(3):
shop = PetShop(get_factory())
shop.show_pet()
print("=" * 20)

工厂方法模式针对的是一个产品等级结构;而抽象工厂模式则是针对的多个产品等级结构。

猫类和狗类的公用方法必须是speak(),不能让猫类的方法名是miaomiao()   ,狗类的方法叫wangwang(),把它当鸭子类,在java是用实现接口来规范。py没有接口。

最新文章

  1. Entity Framework Code First关系映射约定
  2. [Excel] 打印设置
  3. CreateFile函数详解
  4. Linux覆盖率一点研究:获取覆盖率数据
  5. Joblogs——ContentValues的使用
  6. [virsh] error: unknown OS type hvm解决办法
  7. PHP-POSIX正则表达式函数
  8. Linux 的启动流程
  9. ArrayList和List之间的转换
  10. apache 工作模式
  11. iOS基础框架的搭建 / 及国际化操作
  12. 【译】延迟加载JavaScript
  13. Ch1. Intro to Programming
  14. 【Canal源码分析】TableMetaTSDB
  15. It was not possible to find any compatible framework version
  16. Daily Scrum & Project Team Meeting Review - 11/27
  17. python---django使用数据库(orm)
  18. struts2标签类别
  19. EXP-00056:遇到oracle错误12154
  20. 查询避免Unknown column ‘xxx’ in ‘where clause’

热门文章

  1. db2 表空间容量
  2. Spark Client启动原理探索
  3. 【OpenCV】选择ROI区域 (转)
  4. 微软BI 之SSIS 系列 - Lookup 组件的使用与它的几种缓存模式 - Full Cache, Partial Cache, NO Cache
  5. ionic build - 修改gradle路径提升速度和成功率
  6. nginx启动常遇到的问题
  7. Tuxedo低版本客户端(Tuxedo 9)连接到高版本Tuxedo服务端(Tuxedo 12.1.3)的问题
  8. 阿里云Logtail 快速诊断工具
  9. 如何在 Github 上发现优秀的开源项目?
  10. (转)超过 130 个你需要了解的 vim 命令