博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Factory Method(工厂方法)
阅读量:4678 次
发布时间:2019-06-09

本文共 1058 字,大约阅读时间需要 3 分钟。

Factory Method(工厂方法)

意图:

定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使个类的实例化延迟到其子类。

适用性:

当一个类不知道它所必须创建的对象的类的时候。

当一个类希望由它的子类来指定它所创建的对象的时候。

当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。

实现:

#!/usr/bin/python#coding:utf8'''Factory Method''' class ChinaGetter:    """A simple localizer a la gettext"""    def __init__(self):        self.trans = dict(dog=u"小狗", cat=u"小猫")     def get(self, msgid):        """We'll punt if we don't have a translation"""        try:            return self.trans[msgid]        except KeyError:            return str(msgid)  class EnglishGetter:    """Simply echoes the msg ids"""    def get(self, msgid):        return str(msgid)  def get_localizer(language="English"):    """The factory method"""    languages = dict(English=EnglishGetter, China=ChinaGetter)    return languages[language]() # Create our localizerse, g = get_localizer("English"), get_localizer("China")# Localize some textfor msgid in "dog parrot cat bear".split():    print(e.get(msgid), g.get(msgid))

 

转载于:https://www.cnblogs.com/navysummer/p/9835084.html

你可能感兴趣的文章
Windows store 验证你的 URL http:// 和 https:// ms-appx:/// ms-appdata:///local
查看>>
python全栈开发_day7_字符编码,以及文件的基本读取
查看>>
js 验证码 倒计时60秒
查看>>
C#基础
查看>>
ASP.NET Core MVC 2.x 全面教程_ASP.NET Core MVC 15. 用户管理
查看>>
杭电3466————DP之01背包(对状态转移方程的更新理解)
查看>>
算法分析常用记号
查看>>
spring mvc 返回类型
查看>>
[js高手之路] html5 canvas动画教程 - 匀速运动
查看>>
11.VS2015常用快捷键大全
查看>>
js学习总结----less常用的方法
查看>>
需求分析问卷调查及反馈结果
查看>>
当深度学习遇见自动文本摘要
查看>>
心随手动,驱动短视频热潮的引擎
查看>>
Servlet深入之初始化
查看>>
python中出现IndentationError:unindent does not match any outer indentation level错误
查看>>
<mvc:annotation-driven />与<context:annotation-config/>
查看>>
【UML】概念、关联、画画(一)
查看>>
由于空间,注定的结果——第五届山东省ACM编程比赛总结
查看>>
Android复制iPhone日期和时间选择器
查看>>