程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Design pattern factory method - Python

編輯:Python

The factory method is the design pattern , A way of creating design patterns .

It allows interfaces or classes to create objects , But let subclasses decide which class or object to instantiate .

The factory approach provides a better way , Create objects ( There is no need to change the code logic of the client ).

Take a look at an example of a language translation model creation class .

Look at the code that doesn't use the factory pattern :

class FrenchLocalizer:
""" Translate the information into French """
def __init__(self):
self.translations = {
"car": "voiture", "bike": "bicyclette",}
def localize(self, msg):
"""change the message using translations"""
return self.translations.get(msg, msg)
class SpanishLocalizer:
""" Translate the information into Spanish """
def __init__(self):
self.translations = {
"car": "coche", "bike": "bicicleta",}
def localize(self, msg):
""" Translate corresponding information """
return self.translations.get(msg, msg)
if __name__ == "__main__":
# Create class instances 
f = FrenchLocalizer()
s = SpanishLocalizer()
# Input information 
message = ["car", "bike"]
# Output information 
for msg in message:
print(f.localize(msg))
print(s.localize(msg))

Code using factory mode :

class FrenchLocalizer:
""" Translate the information into French """
def __init__(self):
self.translations = {
"car": "voiture", "bike": "bicyclette",}
def localize(self, msg):
""" Translate corresponding information """
return self.translations.get(msg, msg)
class SpanishLocalizer:
""" Translate the information into Spanish """
def __init__(self):
self.translations = {
"car": "coche", "bike": "bicicleta",}
def localize(self, msg):
""" Translate corresponding information """
return self.translations.get(msg, msg)
# Create factory mode 
def Factory(language ="French"):
"""Factory Method"""
localizers = {

"French": FrenchLocalizer,
"Spanish": SpanishLocalizer,
}
return localizers[language]()
if __name__ == "__main__":
f = Factory("French")
s = Factory("Spanish")
message = ["car", "bike"]
for msg in message:
print(f.localize(msg))
print(s.localize(msg))

If you want to add more language version modules , Just add the corresponding class .

Then add the dictionary index of the corresponding class in the factory pattern , Can finish , This process does not require changing the client code .

advantage :

  • We can easily add new types of products , Without interfering with existing client code .
  • Avoid tight coupling between the product and the creator classes and objects .

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved