python设计模式 -- Factory

目的

  • 对创建对象的封装
  • 定义创建对象的接口让子类选择实例化,将类的实例化延迟到子类

简单实现

http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

class GreekLocalizer:
    """模拟一个简单的希腊文本地化"""

    def __init__(self):
        self.translations = {"dog": "σκύλος", "cat": "γάτα"}

    def localize(self, msg):
        """简单翻译,没有翻译原样输出"""
        return self.translations.get(msg, msg)


class EnglishLocalizer:
    """直接回复"""

    def localize(self, msg):
        return msg


def get_localizer(language="English"):
    """工厂"""
    localizers = {
        "English": EnglishLocalizer,
        "Greek": GreekLocalizer,
    }
    return localizers[language]()


def main():
    e, g = get_localizer(language="English"), get_localizer(language="Greek")

    for msg in "dog parrot cat bear".split():
        print(e.localize(msg), g.localize(msg))


if __name__ == "__main__":
    main()


“世界就像是个巨大的马戏团,它让你兴奋,却让我惶恐,因为我知道散场后永远是有限温存,无限心酸。”——Charlie Chaplin