设计模式 -创建型模式 ,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 中最常用的设计模式之一.这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式. 在工厂模式中,我们在创建对象时不会对客户端暴露创建逻 ...
随机推荐
- libctemplate——源码分析
前言 在阅读此文章前,建议先阅读我之前写的<libctemplate——C语言模块引擎简介及使用>,以便对这个库有一个初步的认识.通过对库的代码阅读,对库有了一定的认识,提练一些重要的知识 ...
- 理解TCP之Keepalive
理解HTTP之keep-alive 在前面一篇文章中讲了TCP的keepalive,这篇文章再讲讲HTTP层面keep-alive.两种keepalive在拼写上面就是不一样的,只是发音一样,于是乎大 ...
- boost 线程安全队列
threadnullmethodsprocessingobjectsignal // QueueImplementation.cpp : Defines the entry point for the ...
- Linux终端记录神器
我们在调试程序的时候,免不了要去抓一些 log ,然后进行分析.如果 log 量不是很大的话,那很简单,只需简单的复制粘贴就好.但是如果做一些压力测试,产生大量 log ,而且系统内存又比较小(比如嵌 ...
- linux,日志查找技巧
1.查询日志中含有某个关键字的信息 cat app.log |grep 'error' 2.查询日志尾部最后10行的日志 tail -n 10 app.log 3.查询10行之后的所有日志 tail ...
- 1209 -The MySQL server is running with the --read-only option
1209 - The MySQL server is running with the --read-only option so it cannot execute this statement ...
- [javase学习笔记]-6.2 类与对象的关系
这一节我们来看一下类与对象之间的关系. 我们学习java语言,目的就是用java语言对现实生活中的事物进行描写叙述.那么我们如何来描写叙述呢.这就引出了类,我们在实际实现时,是通过类的形式来体现的. ...
- supervisor //todo
#安装easy-installyum install python-setuptools #安装 supervisoreasy_install supervisor #创建主配置文件echo_supe ...
- 二值化函数cvThreshold()参数CV_THRESH_OTSU的疑惑【转】
查看OpenCV文档cvThreshold(),在二值化函数cvThreshold(const CvArr* src, CvArr* dst, double threshold, double max ...
- 游戏编程精粹学习 - 使用Bloom过滤来提高计算性能(BloomFilter)
原文在<游戏编程精粹2>的1.2中,BloomFilter是一种可以快速检测是否存在集合包含关系的数据结构,但有一定的误识别率. 该结构的优点 判断包含关系时效率较高,粗略测试了下比Lis ...