第 1 章 工厂模式
1.1 工厂方法
DEMO
import xml.etree.ElementTree as etree
import json
# 负责 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 修饰器使其看上去像是一个变量而不是函数
@property
def parsed_data(self):
return self.data
# 负责 XML 解析
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')
# 测试 xml 解析
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)))
# 测试 JSON 解析
json_factory = connect_to('data/donut.json')
json_data = json_factory.parsed_data
print('found: {} donuts'.format(len(json_data)))
if __name__ == '__main__':
main()1.2 抽象工厂
DEMO
1.3 小结
Last updated