Python版

https://github.com/faif/python-patterns/blob/master/behavioral/catalog.py

#!/usr/bin/env python
# -*- coding: utf-8 -*- """
A class that uses different static function depending of a parameter passed in
init. Note the use of a single dictionary instead of multiple conditions
""" __author__ = "Ibrahim Diop <ibrahim@sikilabs.com>" class Catalog(object):
"""catalog of multiple static methods that are executed depending on an init parameter
""" def __init__(self, param): # dictionary that will be used to determine which static method is
# to be executed but that will be also used to store possible param
# value
self._static_method_choices = {'param_value_1': self._static_method_1,
'param_value_2': self._static_method_2} # simple test to validate param value
if param in self._static_method_choices.keys():
self.param = param
else:
raise ValueError("Invalid Value for Param: {0}".format(param)) @staticmethod
def _static_method_1():
print("executed method 1!") @staticmethod
def _static_method_2():
print("executed method 2!") def main_method(self):
"""will execute either _static_method_1 or _static_method_2 depending on self.param value
"""
self._static_method_choices[self.param]() # Alternative implementation for different levels of methods
class CatalogInstance(object): """catalog of multiple methods that are executed depending on an init parameter
""" def __init__(self, param):
self.x1 = 'x1'
self.x2 = 'x2'
# simple test to validate param value
if param in self._instance_method_choices:
self.param = param
else:
raise ValueError("Invalid Value for Param: {0}".format(param)) def _instance_method_1(self):
print("Value {}".format(self.x1)) def _instance_method_2(self):
print("Value {}".format(self.x2)) _instance_method_choices = {'param_value_1': _instance_method_1,
'param_value_2': _instance_method_2} def main_method(self):
"""will execute either _instance_method_1 or _instance_method_2 depending on self.param value
"""
self._instance_method_choices[self.param].__get__(self)() class CatalogClass(object): """catalog of multiple class methods that are executed depending on an init parameter
""" x1 = 'x1'
x2 = 'x2' def __init__(self, param):
# simple test to validate param value
if param in self._class_method_choices:
self.param = param
else:
raise ValueError("Invalid Value for Param: {0}".format(param)) @classmethod
def _class_method_1(cls):
print("Value {}".format(cls.x1)) @classmethod
def _class_method_2(cls):
print("Value {}".format(cls.x2)) _class_method_choices = {'param_value_1': _class_method_1,
'param_value_2': _class_method_2} def main_method(self):
"""will execute either _class_method_1 or _class_method_2 depending on self.param value
"""
self._class_method_choices[self.param].__get__(None, self.__class__)() class CatalogStatic(object): """catalog of multiple static methods that are executed depending on an init parameter
""" def __init__(self, param):
# simple test to validate param value
if param in self._static_method_choices:
self.param = param
else:
raise ValueError("Invalid Value for Param: {0}".format(param)) @staticmethod
def _static_method_1():
print("executed method 1!") @staticmethod
def _static_method_2():
print("executed method 2!") _static_method_choices = {'param_value_1': _static_method_1,
'param_value_2': _static_method_2} def main_method(self):
"""will execute either _static_method_1 or _static_method_2 depending on self.param value
"""
self._static_method_choices[self.param].__get__(None, self.__class__)() def main():
"""
>>> c = Catalog('param_value_1').main_method()
executed method 1!
>>> Catalog('param_value_2').main_method()
executed method 2!
""" test = Catalog('param_value_2')
test.main_method() test = CatalogInstance('param_value_1')
test.main_method() test = CatalogClass('param_value_2')
test.main_method() test = CatalogStatic('param_value_1')
test.main_method() if __name__ == "__main__": main() ### OUTPUT ###
# executed method 2!
# Value x1
# Value x2
# executed method 1!

Python转载版

【编程思想】【设计模式】【行为模式Behavioral】catalog的更多相关文章

  1. 面向对象编程思想(前传)--你必须知道的javascript

    在写面向对象编程思想-设计模式中的js部分的时候发现很多基础知识不了解的话,是很难真正理解和读懂js面向对象的代码.为此,在这里先快速补上.然后继续我们的面向对象编程思想-设计模式. 什么是鸭子类型 ...

  2. 面向对象编程思想(前传)--你必须知道的javascript(转载)

    原文地址:http://www.cnblogs.com/zhaopei/p/6623460.html阅读目录   什么是鸭子类型 javascript的面向对象 封装 继承 多态 原型 this指向 ...

  3. Java编程思想重点笔记(Java开发必看)

    Java编程思想重点笔记(Java开发必看)   Java编程思想,Java学习必读经典,不管是初学者还是大牛都值得一读,这里总结书中的重点知识,这些知识不仅经常出现在各大知名公司的笔试面试过程中,而 ...

  4. PHP设计模式-策略模式 转

    策略模式(Strategy Pattern) 策略模式是对象的行为模式,用意是对一组算法的封装.动态的选择需要的算法并使用. 策略模式指的是程序中涉及决策控制的一种模式.策略模式功能非常强大,因为这个 ...

  5. .NET设计模式: 工厂模式

    .NET设计模式: 工厂模式(转) 转自:http://www.cnblogs.com/bit-sand/archive/2008/01/25/1053207.html   .NET设计模式(1): ...

  6. 面向对象编程思想(OOP)

    本文我将从面向对象编程思想是如何解决软件开发中各种疑难问题的角度,来讲述我们面向对象编程思想的理解,梳理面向对象四大基本特性.七大设计原则和23种设计模式之间的关系. 软件开发中疑难问题: 软件复杂庞 ...

  7. java编程思想

    Java编程思想,Java学习必读经典,不管是初学者还是大牛都值得一读,这里总结书中的重点知识,这些知识不仅经常出现在各大知名公司的笔试面试过程中,而且在大型项目开发中也是常用的知识,既有简单的概念理 ...

  8. 设计模式 之 Organizing the Catalog 组织目录

    Design patterns vary in their granularity and level of abstraction. Because thereare many design pat ...

  9. 设计模式 --迭代器模式(Iterator)

    能够游走于聚合内的每一个元素,同时还可以提供多种不同的遍历方式.   基本概念: 就是提供一种方法顺序访问一个聚合对象中的各个元素,而不是暴露其内部的表示.   使用迭代器模式的优点: 遍历集合或者数 ...

随机推荐

  1. JAVA POI导出EXCEL 动态表头、多级表头、动态数据

    导出Excel文件是业务中经常遇到的需求,以下是经常遇到的一些问题: 1,导出中文文件名乱码 String filename = "sheet1";response.setChar ...

  2. 记一次性能优化的心酸历程【Flask+Gunicorn+pytorch+多进程+线程池,一顿操作猛如虎】

    您好,我是码农飞哥,感谢您阅读本文,欢迎一键三连哦. 本文只是记录我优化的心酸历程.无他,唯记录尔.....小伙伴们可围观,可打call,可以私信与我交流. 干货满满,建议收藏,需要用到时常看看. 小 ...

  3. 从源码分析 XtraBackup 的备份原理

    MySQL物理备份工具,常用的有两个:MySQL Enterprise Backup 和 XtraBackup. 前者常用于MySQL企业版,后者常用于MySQL社区版.Percona Server ...

  4. Salesforce Consumer Goods Cloud 浅谈篇二之门店产品促销的配置

    本篇参考:https://documentation.b2c.commercecloud.salesforce.com/DOC1/index.jsp?topic=%2Fcom.demandware.d ...

  5. python中jsonpath模块,解析多层嵌套的json数据

    1. jsonpath介绍用来解析多层嵌套的json数据;JsonPath 是一种信息抽取类库,是从JSON文档中抽取指定信息的工具,提供多种语言实现版本,包括:Javascript, Python, ...

  6. python实现膨胀与腐蚀

    目录: (一)膨胀 (二)腐蚀 (三)腐蚀代码(erode) (四)膨胀代码(dilate) (一)膨胀(或) (二)腐蚀(与) (三)腐蚀代码(erode) 1 def erode_demo(ima ...

  7. JVM 是用什么语言写的?

    JAVA中就虚拟机是其它语言开发的,用的是C语言+汇编语言  基于此之上就是JAVA本身了  虚拟机只起到解析作用另外,JAVA并不比C语言慢,说JAVA慢一般是九十年代那时候的JAVA, 而现在 在 ...

  8. [atAGC049F]Happy Sequence

    定义$L=2\cdot 10^{5}$,$g(x)=\sum_{i=1}^{n}|b_{i}-x|-|a_{i}-x|$,则合法当且仅当$\forall 0\le x\le L,g(x)\ge 0$, ...

  9. NFLSOJ #10317. -「2020联考北附2」三千世界(找等价表达+树形 dp)

    题面传送门 出题人可能原本感觉没啥难度的 T2 竟然变成了防 AK 题,奇迹奇迹( 首先带着这个 \(\max\) 肯定不太好处理,考虑找出 \(f(S)\) 的等价表达.我们考虑以 \(1\) 为根 ...

  10. 【豆科基因组】小豆(红豆)adzuki bean, Vigna angularis基因组2015

    目录 一.来源 研究一:Draft genome sequence of adzuki bean, Vigna angularis 研究二:Genome sequencing of adzuki be ...