Ai
1 Star 0 Fork 0

imoyao/python-patterns

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
factory.py 2.17 KB
一键复制 编辑 原始数据 按行查看 历史
Mateus Furquim 提交于 2023-01-21 00:24 +08:00 . Add Protocol to factory pattern
"""*What is this pattern about?
A Factory is an object for creating other objects.
*What does this example do?
The code shows a way to localize words in two languages: English and
Greek. "get_localizer" is the factory function that constructs a
localizer depending on the language chosen. The localizer object will
be an instance from a different class according to the language
localized. However, the main code does not have to worry about which
localizer will be instantiated, since the method "localize" will be called
in the same way independently of the language.
*Where can the pattern be used practically?
The Factory Method can be seen in the popular web framework Django:
https://docs.djangoproject.com/en/4.0/topics/forms/formsets/
For example, different types of forms are created using a formset_factory
*References:
http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
*TL;DR
Creates objects without having to specify the exact class.
"""
from typing import Dict
from typing import Protocol
from typing import Type
class Localizer(Protocol):
def localize(self, msg: str) -> str:
pass
class GreekLocalizer:
"""A simple localizer a la gettext"""
def __init__(self) -> None:
self.translations = {"dog": "σκύλος", "cat": "γάτα"}
def localize(self, msg: str) -> str:
"""We'll punt if we don't have a translation"""
return self.translations.get(msg, msg)
class EnglishLocalizer:
"""Simply echoes the message"""
def localize(self, msg: str) -> str:
return msg
def get_localizer(language: str = "English") -> Localizer:
"""Factory"""
localizers: Dict[str, Type[Localizer]] = {
"English": EnglishLocalizer,
"Greek": GreekLocalizer,
}
return localizers[language]()
def main():
"""
# Create our localizers
>>> e, g = get_localizer(language="English"), get_localizer(language="Greek")
# Localize some text
>>> for msg in "dog parrot cat bear".split():
... print(e.localize(msg), g.localize(msg))
dog σκύλος
parrot parrot
cat γάτα
bear bear
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/imoyao/python-patterns.git
git@gitee.com:imoyao/python-patterns.git
imoyao
python-patterns
python-patterns
master

搜索帮助