设计模式 -创建型模式 ,python工厂模式 抽象工厂模式(1)
工厂模式 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没有接口。
设计模式 -创建型模式 ,python工厂模式 抽象工厂模式(1)的更多相关文章
- 设计模式----创建型模式之工厂模式(FactoryPattern)
工厂模式主要分为三种简单工厂模式.工厂方法模式.抽象工厂模式三种.顾名思义,工厂主要是生产产品,作为顾客或者商家,我们不考虑工厂内部是怎么一个流程,我们要的是最终产品.将该种思路放在我们面向对象开发实 ...
- C# 设计模式·创建型模式
面试问到这个··答不出来就是没有架构能力···这里学习一下···面试的时候直接让我说出26种设计模式··当时就懵逼了··我记得好像之前看的时候是23种的 还有3个是啥的··· 这里先列出几种创建型模式 ...
- 详解设计模式之工厂模式(简单工厂+工厂方法+抽象工厂) v阅读目录
1楼留头头大神:http://www.cnblogs.com/toutou/p/4899388.html v阅读目录 v写在前面 v简单工厂模式 v工厂方法模式 v抽象工厂模式 v博客总结 v博客 ...
- Java设计模式之-----工厂模式(简单工厂,抽象工厂)
一.工厂模式主要是为创建对象提供过渡接口,以便将创建对象的具体过程屏蔽隔离起来,达到提高灵活性的目的. 工厂模式在<Java与模式>中分为三类:1)简单工厂模式(Simple Factor ...
- Java 工厂模式(一)— 抽象工厂(Abstract Factory)模式
一.抽象工厂模式介绍: 1.什么是抽象工厂模式: 抽象工厂模式是所有形态的工厂模式中最为抽象和最具有一般性的一种形态,抽象工厂模式向客户端提供一个接口,使得客户端在不知道具体产品的情类型的情况下,创建 ...
- 设计模式--简单工厂VS工厂VS抽象工厂
前几天我一直在准备大学毕业生,始终绑起来,如今,终于有时间去学习设计模式.我们研究今天的话题是植物三口之家的设计模式的控制--简单工厂VS工厂VS抽象工厂. 经过细心推敲,我们不难得出:工厂模式是简单 ...
- Head First设计模式——简单工厂、工厂、抽象工厂
前言:按照惯例我以Head First设计模式的工厂模式例子开始编码学习.并由简单工厂,工厂模式,抽象工厂模式依次演变,归纳他们的相同与不同. 话说Head First认为简单工厂并不是设计模式,而是 ...
- php设计模式课程---3、为什么会有抽象工厂方法
php设计模式课程---3.为什么会有抽象工厂方法 一.总结 一句话总结: 解决简单工厂方法增加新选择时无法满足面向对象编程中的开闭原则问题 1.什么是面向对象编程中的开闭原则? 应该对类的增加开放, ...
- 【python设计模式-创建型】工厂方法模式
工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一.这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式. 在工厂模式中,我们在创建对象时不会对客户端暴露创建逻 ...
随机推荐
- Jenkins配置基于角色的项目权限管理
转自: http://www.cnblogs.com/gao241/archive/2013/03/20/2971416.html, 版权归原作者. 本文将介绍如何配置jenkins,使其可以支持基于 ...
- makefile中的shell编程注意点
参考:http://blog.csdn.net/wanglang3081/article/details/49423105 (1)Makefile本质上来讲也是shell脚本,即每条command都是 ...
- 17、python对内存的使用
python对内存的使用 浅拷贝和深拷贝 所谓浅拷贝就是对引用的拷贝(只拷贝父对象) 所谓深拷贝就是对对象的资源的拷贝 解释一个例子: import copy a = [1,2,3,['a','b', ...
- (转) Java RandomAccessFile与MappedByteBuffer
RandomAccessFile RandomAccessFile是用来访问那些保存数据记录的文件的,你就可以用seek( )方法来访问记录,并进行读写了.这些记录的大小不必相同:但是其大小和位置必须 ...
- centos清除dns cache.
# /etc/init.d/nscd restart # service nscd restart # service nscd reload # nscd -i hosts https://www. ...
- how to use boost program options
From: http://www.radmangames.com/programming/how-to-use-boost-program_options If it so happens that ...
- PL/SQL出现存储过程注释中文乱码
进入PL/SQL命令行窗口输入:select userenv('language') from dual 查出数据库字符集 输入:select * from V$NLS_PARAMETERS 查出NL ...
- iBatis resultMap报错 nullValue完美解决
http://blog.csdn.net/liguohuaty/article/details/4038437
- 搞定所有的跨域请求问题 jsonp CORS
网上各种跨域教程,各种实践,各种问答,除了简单的 jsonp 以外,很多说 CORS 的都是行不通的,老是缺那么一两个关键的配置.本文只想解决问题,所有的代码经过亲自实践. 本文解决跨域中的 ge ...
- 安装配置OSA运维管理平台
1.下载完整包V1.0.2wget http://www.osapub.com/download/OSA_BETA_V1.0.2.tar.gzV1.0.5wget http://www.osapub. ...