Python中怎样实现工厂模式
短信预约 -IT技能 免费直播动态提醒
本篇文章给大家分享的是有关Python中怎样实现工厂模式,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
如下是工厂方法的实现,里面用到了字典来做键值的映射。
#!/usr/bin/python# coding:utf8 '''Factory Method ''' class ChinaGetter: """A simple localizer a la gettext""" def __init__(self): self.trans = dict(jianrong=u"杨建荣", jianrong_notes=u"学习笔记") def get(self, msgid): """We'll punt if we don't have a translation""" try: return self.trans[msgid] except KeyError: return str(msgid) class EnglishGetter: """Simply echoes the msg ids""" def __init__(self): self.trans = dict(jeanron100=u"jeanron100...", mysql=u"MySQL", oracle=u"Oracle") def get(self, msgid): try: return self.trans[msgid] except KeyError: return str(msgid) def get_localizer(language="English"): """The factory method""" languages = dict(English=EnglishGetter, China=ChinaGetter) return languages[language]() # Create our localizerse, g = get_localizer("English"), get_localizer("China") # Localize some text for msgid in "jeanron100 jianrong mysql oracle".split(): print(e.get(msgid), g.get(msgid))
执行结果如下:
(u'jeanron100...', 'jeanron100')
('jianrong', u'\u6768\u5efa\u8363')
(u'MySQL', 'mysql')
(u'Oracle', 'oracle')
而使用抽象工厂,使用了random来做一个动态匹配。这个例子参考了开篇的第一个链接的例子,里面的getFactory方法会随机得到一个工厂的实例化对象,而对于应用来说这个匹配的过程是透明的。
#!/usr/bin/python# coding:utf8 '''Abstract Factory ''' 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("This is a lovely", str(pet)) print("It says", pet.speak()) print("It eats", 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 familydef get_factory(): """Let's be dynamic!""" return random.choice([DogFactory, CatFactory])() # Show pets with various factories if __name__ == "__main__": shop = PetShop() for i in range(3): shop.pet_factory = get_factory() shop.show_pet() print("=" * 20) #print random.choice([1,2,3,4,5])
执行结果如下:
('This is a lovely', 'Cat') ('It says', 'meow') ('It eats', 'cat food') ==================== ('This is a lovely', 'Cat') ('It says', 'meow') ('It eats', 'cat food') ==================== ('This is a lovely', 'Dog') ('It says', 'woof') ('It eats', 'dog food') ====================
以上就是Python中怎样实现工厂模式,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注编程网行业资讯频道。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341