工厂方法是设计模式中,创建设计模式的一种设计方式。
它允许接口或类创建对象,但让子类决定要实例化哪个类或对象。
工厂方法提供了一种更好的方式,创建对象(不需要更改客户端的代码逻辑)。
看一个语言翻译模型创建类的例子。
看一下不使用工厂模式的代码:
class FrenchLocalizer:
""" 将信息翻译为法语版本"""
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:
"""将信息翻译为西班牙语版本"""
def __init__(self):
self.translations = {"car": "coche", "bike": "bicicleta",}
def localize(self, msg):
"""翻译对应信息"""
return self.translations.get(msg, msg)
if __name__ == "__main__":
# 创建类实例
f = FrenchLocalizer()
s = SpanishLocalizer()
# 输入信息
message = ["car", "bike"]
#输出信息
for msg in message:
print(f.localize(msg))
print(s.localize(msg))
使用工厂模式的代码:
class FrenchLocalizer:
""" 将信息翻译为法语版本"""
def __init__(self):
self.translations = {"car": "voiture", "bike": "bicyclette",}
def localize(self, msg):
"""翻译对应信息"""
return self.translations.get(msg, msg)
class SpanishLocalizer:
""" 将信息翻译为西班牙语版本"""
def __init__(self):
self.translations = {"car": "coche", "bike": "bicicleta",}
def localize(self, msg):
"""翻译对应信息"""
return self.translations.get(msg, msg)
#创建工厂模式
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))
如果想要添加更多的语言版本模块,只需要添加对应的类。
然后在工厂模式中添加对应类的字典索引,即可完成,这个过程不需要改变客户端的代码。
优点:
- 我们可以轻松添加新类型的产品,而不会干扰现有的客户端代码。
- 避免产品与创建者类和对象之间的紧密耦合。