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>