溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python中怎樣實現(xiàn)工廠模式

發(fā)布時間:2021-08-10 15:22:57 來源:億速云 閱讀:178 作者:Leah 欄目:編程語言

本篇文章給大家分享的是有關Python中怎樣實現(xiàn)工廠模式,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

如下是工廠方法的實現(xiàn),里面用到了字典來做鍵值的映射。

#!/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 localizers
e, 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))

執(zhí)行結果如下:

(u'jeanron100...', 'jeanron100')

('jianrong', u'\u6768\u5efa\u8363')

(u'MySQL', 'mysql')

(u'Oracle', 'oracle')

而使用抽象工廠,使用了random來做一個動態(tài)匹配。這個例子參考了開篇的第一個鏈接的例子,里面的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 family
def 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])

執(zhí)行結果如下:

('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中怎樣實現(xiàn)工廠模式,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI