(一)工廠模式運用場景
若需要將物件的建立和使用解耦,工廠方法也能派上用場。
工廠方法可以在必要時建立新的物件,從而提高效能和記憶體使用率。
(二)工廠模式案例
import xml.etree.elementtree as etree
import json
class jsonconnector:
def __init__(self, filepath):
self.data = dict()
with open(filepath, mode='r') 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
if __name__ == '__main__':
# 要那個傳哪個,不占用記憶體
sqlite_factory = connect_to('person.sq3')
xml_factory = connect_to('person.xml')
json_factory = connect_to('person.json')
(一)什麼事抽象工廠
乙個抽象工廠是(邏輯上的)一組工廠方法,其中的每個工廠方法負責產生不同種類的物件。(二)應用場景
(三)應用案例
class frog: # 青蛙類
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def interact_with(self, obstacle):
print('{} the frog encounters {} and {}!'.format(self,
obstacle, obstacle.action()))
class bug: # 蟲子類
def __str__(self):
return 'a bug'
def action(self):
return 'eats it'
class frogworld: # 青蛙遊戲
def __init__(self, name):
print(self)
self.player_name = name
def __str__(self):
return '\n\n\t------ frog world -------'
def make_character(self):
return frog(self.player_name)
def make_obstacle(self):
return bug()
class wizard: # 男巫類
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def interact_with(self, obstacle):
print('{} the wizard battles against {} and {}!'.format(self, obstacle, obstacle.action()))
class ork: # 獸人
def __str__(self):
return 'an evil ork'
def action(self):
return 'kills it'
class wizardworld: # 男巫遊戲
def __init__(self, name):
print(self)
self.player_name = name
def __str__(self):
return '\n\n\t------ wizard world -------'
def make_character(self):
return wizard(self.player_name)
def make_obstacle(self):
return ork()
class gameenvironment:
def __init__(self, factory):
self.hero = factory.make_character()
self.obstacle = factory.make_obstacle()
def play(self):
self.hero.interact_with(self.obstacle)
def validate_age(name):
try:
age = raw_input('welcome {}. how old are you? '.format(name))
age = int(age)
except valueerror as err:
print("age {} is invalid, please try again...".format(age))
return (false, age)
return (true, age)
def main():
name = raw_input("hello. what's your name? ")
valid_input = false
while not valid_input:
valid_input, age = validate_age(name)
game = frogworld if age < 18 else wizardworld
environment = gameenvironment(game(name))
environment.play()
if __name__ == '__main__':
main()
Python設計模式之工廠模式
工廠模式,可以理解為建立乙個工廠 類 這個工廠會根據你的需求 輸入 生產出 輸出 你想要的產品 物件 簡單說就是工廠類會根據你的輸入給你返回恰當的物件。class shape staticmethod deffactory shape if shape square return square if...
python設計模式之工廠模式
from abc import abcmeta,abstractmethod class coke metaclass abcmeta abstractmethod defdrink self pass class coca coke defdrink self print drink coca c...
設計模式學習之工廠模式
工廠模式,factorymethod,定義乙個工廠類的基類,基類中不再去實現具體的產品類的例項,而是將產品類的例項化工作放在其子類中進行,然後由客戶端來決定要使用那一種產品類的例項,工廠模式也要求產品類都具有相同的產品基類,這和簡單工廠模式比較相似。個人理解 工廠模式和簡單模式最大的區別是將產品類的...