python simple factory mode example
Two python simple factory mode examples shown in this section. One is for base operation and another is for json and xml file handling.
1. Base operation script shown as following:
- # -*- coding: utf-8 -*-
- """
OperationFactory.py- This is a simple python3 factory mode example for operation
- Created on Thu Sep 20 14:53:22 2018
- """
- __author__="lyp"
- class Operation:
- def __init__(self,Num1,Num2):
- self.Num1=Num1
- self.Num2=Num2
- class OperationAdd(Operation):
- def __init__(self,Num1,Num2):
- Operation.__init__(self,Num1,Num2)
- def result(self):
- return(self.Num1+self.Num2)
- class OperationSub(Operation):
- def __init__(self,Num1,Num2):
- Operation.__init__(self,Num1,Num2)
- def result(self):
- return(self.Num1-self.Num2)
- class OperationMul(Operation):
- def __init__(self,Num1,Num2):
- Operation.__init__(self,Num1,Num2)
- def result(self):
- return(self.Num1*self.Num2)
- class OperationDiv(Operation):
- def __init__(self,Num1,Num2):
- Operation.__init__(self,Num1,Num2)
- def result(self):
- if self.Num2==0:
- raise ValueError("Num2 can't be 0!!!")
- else:
- return(self.Num1/self.Num2)
- class OperationFactory:
- def __init__(self):
- pass
- def create_operation(self,string_operate):
- self.string_operate=string_operate
- if self.string_operate=="+":
- return(OperationAdd)
- elif self.string_operate=="-":
- return(OperationSub)
- elif self.string_operate=="*":
- return(OperationMul)
- elif self.string_operate=="/":
- return(OperationDiv)
- else:
- raise ValueError("Operator Error!!!")
- def main():
- Add=OperationFactory().create_operation("+")
- value=Add(1.0,2).result()
- print("Add value is: {}".format(value))
- Sub=OperationFactory().create_operation("-")
- value=Sub(1.0,2).result()
- print("Sub value is: {}".format(value))
- Mul=OperationFactory().create_operation("*")
- value=Mul(1.0,2).result()
- print("Mul value is: {}".format(value))
- Div=OperationFactory().create_operation("/")
- value=Div(1.0,2).result()
- print("Div value is: {}".format(value))
- if __name__=="__main__":
- main()
result as below:
- Add value is: 3.0
- Sub value is: -1.0
- Mul value is: 2.0
- Div value is: 0.5
Fig1.UML picture for OperationFactory.py
2. Connector factory script shown as following:
- # -*- coding: utf-8 -*-
- """
- ConnectorFactory.py
- """
- __author__="lyp"
- import json
- import xml.etree.ElementTree as etree
- import os
- class jsonconnector:
- def __init__(self,filepath):
- self.data=[]
- with open(filepath,mode='r',encoding='utf-8') as f:
- self.data=json.load(f)
- def parsed_data(self):
- return self.data
- class xmlconnector:
- def __init__(self,filepath):
- self.tree=etree.parse(filepath)
- def parsed_data(self):
- return self.tree
- def connector_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=connector_factory(filepath)
- except ValueError as ve:
- print(ve)
- return factory
- def main():
- sql_factory=connect_to(os.getcwd()+os.sep+"sqlexample.sql")
- print(sql_factory)
- json_factory=connect_to(os.getcwd()+os.sep+"jsonexample.json")
- print(json_factory)
- json_data=json_factory.parsed_data()
- print('found: {} donuts'.format(len(json_data)))
- for donuts in json_data:
- print('name: {}'.format(donuts['name']))
- print('price: ${}'.format(donuts['ppu']))
- [print('topping: {} {}'.format(t['id'], t['type'])) for t in donuts['topping']]
- xml_factory=connect_to(os.getcwd()+os.sep+"xmlexample.xml")
- print(xml_factory)
- 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')]
- if __name__=="__main__":
- main()
result as below(Note that sql_factory in main is test for exception handling):
- Cannot connect to C:\Users\sling\Desktop\factory\sqlexample.sql
- None
- <__main__.jsonconnector object at 0x000000000E4DB9B0>
- found: 3 donuts
- name: Cake
- price: $0.55
- topping: 5001 None
- topping: 5002 Glazed
- topping: 5005 Sugar
- topping: 5007 Powdered Sugar
- topping: 5006 Chocolate with Sprinkles
- topping: 5003 Chocolate
- topping: 5004 Maple
- name: Raised
- price: $0.55
- topping: 5001 None
- topping: 5002 Glazed
- topping: 5005 Sugar
- topping: 5003 Chocolate
- topping: 5004 Maple
- name: Old Fashioned
- price: $0.55
- topping: 5001 None
- topping: 5002 Glazed
- topping: 5003 Chocolate
- topping: 5004 Maple
- <__main__.xmlconnector object at 0x000000000E4DB748>
- found: 2 persons
- first name: Jimy
- last name: Liar
- phone number (home) 212 555-1234
- first name: Patty
- last name: Liar
- phone number (home) 212 555-1234
- phone number (mobile) 001 452-8819
3. json file content (jsonexample.json)
- [
- {
- "id": "",
- "type": "donut",
- "name": "Cake",
- "ppu": 0.55,
- "batters": {
- "batter": [
- {
- "id": "",
- "type": "Regular"
- },
- {
- "id": "",
- "type": "Chocolate"
- },
- {
- "id": "",
- "type": "Blueberry"
- },
- {
- "id": "",
- "type": "Devil's Food"
- }
- ]
- },
- "topping": [
- {
- "id": "",
- "type": "None"
- },
- {
- "id": "",
- "type": "Glazed"
- },
- {
- "id": "",
- "type": "Sugar"
- },
- {
- "id": "",
- "type": "Powdered Sugar"
- },
- {
- "id": "",
- "type": "Chocolate with Sprinkles"
- },
- {
- "id": "",
- "type": "Chocolate"
- },
- {
- "id": "",
- "type": "Maple"
- }
- ]
- },
- {
- "id": "",
- "type": "donut",
- "name": "Raised",
- "ppu": 0.55,
- "batters": {
- "batter": [
- {
- "id": "",
- "type": "Regular"
- }
- ]
- },
- "topping": [
- {
- "id": "",
- "type": "None"
- },
- {
- "id": "",
- "type": "Glazed"
- },
- {
- "id": "",
- "type": "Sugar"
- },
- {
- "id": "",
- "type": "Chocolate"
- },
- {
- "id": "",
- "type": "Maple"
- }
- ]
- },
- {
- "id": "",
- "type": "donut",
- "name": "Old Fashioned",
- "ppu": 0.55,
- "batters": {
- "batter": [
- {
- "id": "",
- "type": "Regular"
- },
- {
- "id": "",
- "type": "Chocolate"
- }
- ]
- },
- "topping": [
- {
- "id": "",
- "type": "None"
- },
- {
- "id": "",
- "type": "Glazed"
- },
- {
- "id": "",
- "type": "Chocolate"
- },
- {
- "id": "",
- "type": "Maple"
- }
- ]
- }
- ]
3. xml file content (xmlexample.xml)
- <persons>
- <person>
- <firstName>John</firstName>
- <lastName>Smith</lastName>
- <age>25</age>
- <address>
- <streetAddress>21 2nd Street</streetAddress>
- <city>New York</city>
- <state>NY</state>
- <postalCode>10021</postalCode>
- </address>
- <phoneNumbers>
- <phoneNumber type="home">212 555-1234</phoneNumber>
- <phoneNumber type="fax">646 555-4567</phoneNumber>
- </phoneNumbers>
- <gender>
- <type>male</type>
- </gender>
- </person>
- <person>
- <firstName>Jimy</firstName>
- <lastName>Liar</lastName>
- <age>19</age>
- <address>
- <streetAddress>18 2nd Street</streetAddress>
- <city>New York</city>
- <state>NY</state>
- <postalCode>10021</postalCode>
- </address>
- <phoneNumbers>
- <phoneNumber type="home">212 555-1234</phoneNumber>
- </phoneNumbers>
- <gender>
- <type>male</type>
- </gender>
- </person>
- <person>
- <firstName>Patty</firstName>
- <lastName>Liar</lastName>
- <age>20</age>
- <address>
- <streetAddress>18 2nd Street</streetAddress>
- <city>New York</city>
- <state>NY</state>
- <postalCode>10021</postalCode>
- </address>
- <phoneNumbers>
- <phoneNumber type="home">212 555-1234</phoneNumber>
- <phoneNumber type="mobile">001 452-8819</phoneNumber>
- </phoneNumbers>
- <gender>
- <type>female</type>
- </gender>
- </person>
- </persons>
python simple factory mode example的更多相关文章
- PHP设计模式(一)简单工厂模式 (Simple Factory For PHP)
最近天气变化无常,身为程序猿的寡人!~终究难耐天气的挑战,病倒了,果然,程序猿还需多保养自己的身体,有句话这么说:一生只有两件事能报复你:不够努力的辜负和过度消耗身体的后患.话不多说,开始吧. 一.什 ...
- Design Patterns Simplified - Part 3 (Simple Factory)【设计模式简述--第三部分(简单工厂)】
原文链接:http://www.c-sharpcorner.com/UploadFile/19b1bd/design-patterns-simplified-part3-factory/ Design ...
- 设计模式之简单工厂模式Simple Factory(四创建型)
工厂模式简介. 工厂模式专门负责将大量有共同接口的类实例化 工厂模式可以动态决定将哪一个类实例化,不必事先知道每次要实例化哪一个类. 工厂模式有三种形态: 1.简单工厂模式Simple Factory ...
- Net设计模式实例之简单工厂模式(Simple Factory Pattern)
一.简单工厂模式简介(Bref Introduction) 简单工厂模式(Simple Factory Pattern)的优点是,工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类, ...
- 创建型模式(前引)简单工厂模式Simple Factory
一引出的原因(解决下面的问题) 简单工厂模式(Simple Factory Pattern):又称为静态工厂方法(Static Factory Method)模式,它属于类创建型模式. 在简单工厂模式 ...
- 深入浅出设计模式——简单工厂模式(Simple Factory)
介绍简单工厂模式不能说是一个设计模式,说它是一种编程习惯可能更恰当些.因为它至少不是Gof23种设计模式之一.但它在实际的编程中经常被用到,而且思想也非常简单,可以说是工厂方法模式的一个引导,所以我想 ...
- 设计模式学习之简单工厂(Simple Factory,创建型模式)(1)
简单工厂(Simple Factory,创建型模式) 第一步: 比如我们要采集苹果和香蕉,那么我们需要创建一个Apple类和Banana类,里面各自有采集方法get(),然后通过main方法进行调用, ...
- 设计模式:简单工厂(Simple Factory)
定义:根据提供的数据或参数返回几种可能类中的一种. 示例:实现计算器功能,要求输入两个数和运算符号,得到结果. 结构图: HTML: <html xmlns="http://www.w ...
- Simple Factory vs. Factory Method vs. Abstract Factory【简单工厂,工厂方法以及抽象工厂的比较】
I ran into a question on stackoverflow the other day that sort of shocked me. It was a piece of code ...
随机推荐
- SQLMap-----初识
前言 昨天收到一封来自客户网络中心发来的邮件,说是之前的一个项目存在sql注入漏洞,并附上了一张sqlmap检测结果的图片.记得第一次接触sql注入这些关于系统安全的问题还是从老师口中得知,当时也了解 ...
- python 控制台单行刷新,多行刷新
先贴出单行刷新实现的进度条: 对于控制台的单行刷新,比较简单,先直接贴出代码: strarrs = ['/','|','\\'] for i in range(15): sys.stdout.writ ...
- 基于easyui开发Web版Activiti流程定制器详解(六)——Draw2d的扩展(三)
题外话: 最近在忙公司的云项目空闲时间不是很多,所以很久没来更新,今天补上一篇! 回顾: 前几篇介绍了一下设计器的界面和Draw2d基础知识,这篇讲解一下本设计器如何扩展Draw2d. 进入主题: 先 ...
- 基于easyui开发Web版Activiti流程定制器详解(五)——Draw2d详解(一)
背景: 小弟工作已有十年有余,期间接触了不少工作流产品,个人比较喜欢的还是JBPM,因为出自名门Jboss所以备受推崇,但是现在JBPM版本已经与自己当年使用的版本(3.X)大相径庭,想升级也不太容易 ...
- Django template 过滤器
转载自: http://www.lidongkui.com/django-template-filter-table 一.形式:小写 {{ name | lower }} 二.过滤器是可以嵌套的,字符 ...
- 微软YY公开课[《微软中国云计算Azure平台体验与新企业架构设计》 周六晚9点
YY频道是 52545291//@_勤_: YY账号真的是一次一账号啊! 全然记不得之前注冊的//@老徐FrankXuLei: 最火爆的微软免费公开课.第一次顶峰126人.第二次96人.第三次我们又来 ...
- CF97B Superset
嘟嘟嘟cf 嘟嘟嘟luogu 刚开始我看成了对于一个点\(i\),存在一个点\(j\)满足三个条件之一,而不是任意的\(j\).结果自然\(gg\)了,第二个点就\(WA\)了. 也不知怎么来的思路: ...
- Python学习之路 (三)爬虫(二)
通用爬虫和聚焦爬虫 根据使用场景,网络爬虫可分为 通用爬虫 和 聚焦爬虫 两种. 通用爬虫 通用网络爬虫 是 捜索引擎抓取系统(Baidu.Google.Yahoo等)的重要组成部分.主要目的是将互联 ...
- servlet使用
一.使用IDEAL创建项目 1) 2) 3) 4) 5) 6) 7) 8) 9) 二.路径介绍: 配置文件: servlet配置文件: package ser_Test; import javax.s ...
- 强连通分量算法·$tarjan$初探
嗯,今天好不容易把鸽了好久的缩点给弄完了--感觉好像--很简单? 算法的目的,其实就是在有向图上,把一个强连通分量缩成一个点--然后我们再对此搞搞事情,\(over\) 哦对,时间复杂度很显然是\(\ ...