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 :