Python版

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

#!/usr/bin/env python
# -*- coding: utf-8 -*- """
http://www.dabeaz.com/coroutines/
""" from contextlib import contextmanager
import os
import sys
import time
import abc class Handler(object):
__metaclass__ = abc.ABCMeta def __init__(self, successor=None):
self._successor = successor def handle(self, request):
res = self._handle(request)
if not res:
self._successor.handle(request) @abc.abstractmethod
def _handle(self, request):
raise NotImplementedError('Must provide implementation in subclass.') class ConcreteHandler1(Handler): def _handle(self, request):
if 0 < request <= 10:
print('request {} handled in handler 1'.format(request))
return True class ConcreteHandler2(Handler): def _handle(self, request):
if 10 < request <= 20:
print('request {} handled in handler 2'.format(request))
return True class ConcreteHandler3(Handler): def _handle(self, request):
if 20 < request <= 30:
print('request {} handled in handler 3'.format(request))
return True class DefaultHandler(Handler): def _handle(self, request):
print('end of chain, no handler for {}'.format(request))
return True class Client(object): def __init__(self):
self.handler = ConcreteHandler1(
ConcreteHandler3(ConcreteHandler2(DefaultHandler()))) def delegate(self, requests):
for request in requests:
self.handler.handle(request) def coroutine(func):
def start(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return start @coroutine
def coroutine1(target):
while True:
request = yield
if 0 < request <= 10:
print('request {} handled in coroutine 1'.format(request))
else:
target.send(request) @coroutine
def coroutine2(target):
while True:
request = yield
if 10 < request <= 20:
print('request {} handled in coroutine 2'.format(request))
else:
target.send(request) @coroutine
def coroutine3(target):
while True:
request = yield
if 20 < request <= 30:
print('request {} handled in coroutine 3'.format(request))
else:
target.send(request) @coroutine
def default_coroutine():
while True:
request = yield
print('end of chain, no coroutine for {}'.format(request)) class ClientCoroutine: def __init__(self):
self.target = coroutine1(coroutine3(coroutine2(default_coroutine()))) def delegate(self, requests):
for request in requests:
self.target.send(request) def timeit(func): def count(*args, **kwargs):
start = time.time()
res = func(*args, **kwargs)
count._time = time.time() - start
return res
return count @contextmanager
def suppress_stdout():
try:
stdout, sys.stdout = sys.stdout, open(os.devnull, 'w')
yield
finally:
sys.stdout = stdout if __name__ == "__main__":
client1 = Client()
client2 = ClientCoroutine()
requests = [2, 5, 14, 22, 18, 3, 35, 27, 20] client1.delegate(requests)
print('-' * 30)
client2.delegate(requests) requests *= 10000
client1_delegate = timeit(client1.delegate)
client2_delegate = timeit(client2.delegate)
with suppress_stdout():
client1_delegate(requests)
client2_delegate(requests)
# lets check which is faster
print(client1_delegate._time, client2_delegate._time) ### OUTPUT ###
# request 2 handled in handler 1
# request 5 handled in handler 1
# request 14 handled in handler 2
# request 22 handled in handler 3
# request 18 handled in handler 2
# request 3 handled in handler 1
# end of chain, no handler for 35
# request 27 handled in handler 3
# request 20 handled in handler 2
# ------------------------------
# request 2 handled in coroutine 1
# request 5 handled in coroutine 1
# request 14 handled in coroutine 2
# request 22 handled in coroutine 3
# request 18 handled in coroutine 2
# request 3 handled in coroutine 1
# end of chain, no coroutine for 35
# request 27 handled in coroutine 3
# request 20 handled in coroutine 2
# (0.2369999885559082, 0.16199994087219238)

Python版

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

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

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

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

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

  3. Java设计模式(14)责任链模式(Chain of Responsibility模式)

    Chain of Responsibility定义:Chain of Responsibility(CoR) 是用一系列类(classes)试图处理一个请求request,这些类之间是一个松散的耦合, ...

  4. 深入浅出设计模式——职责链模式(Chain of Responsibility Pattern)

    模式动机 职责链可以是一条直线.一个环或者一个树形结构,最常见的职责链是直线型,即沿着一条单向的链来传递请求.链上的每一个对象都是请求处理者,职责链模式可以将请求的处理者组织成一条链,并使请求沿着链传 ...

  5. 设计模式:职责链模式(Chain Of Responsibility)

    定  义:使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系.将这些对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止. 结构图: 处理请求类: //抽象处理类 abs ...

  6. 23种设计模式之责任链模式(Chain of Responsibility Pattern)

    责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链.这种模式给予请求的类型,对请求的发送者和接收者进行解耦.这种类型的设计模式属于行为型模式. ...

  7. 设计模式之笔记--职责链模式(Chain of Responsibility)

    职责链模式(Chain of Responsibility) 定义 职责链模式(Chain of Responsibility),使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系 ...

  8. 【设计模式】行为型05责任链模式(Chain of responsibility Pattern)

    学习地址:http://www.runoob.com/design-pattern/chain-of-responsibility-pattern.html demo采用了DEBUG级别举例子,理解起 ...

  9. C#设计模式:职责链模式(Chain of Responsibility)

    一,什么是职责链模式(Chain of Responsibility) 职责链模式是一种行为模式,为解除请求的发送者和接收者之间的耦合,而使多个对象都有机会处理这个请求.将这些对象连接成一条链,并沿着 ...

随机推荐

  1. 使用silky脚手架构建微服务应用

    目录 模板简介 构建独立应用的模板Silky.App.Template 构建模块化应用的模板Silky.Module.Template 开源地址 在线文档 模板简介 使用 dotnet new 命令可 ...

  2. Linux常用命令和快捷键整理:(2)常用快捷键

    前言: Linux常用快捷键和基本命令整理,先上思维导图: linux常用命令请见:https://www.cnblogs.com/yinzuopu/p/15516499.html 基本快捷键的使用 ...

  3. msfsploit框架的使用——ms17_010漏洞的利用

    开门见山,首先输入msfconsole打开msf控制台 全球最牛逼的渗透测试框架就是长这个样子(每次打开时,显示的图案都不一样) 然后搜索ms17_010的相关模块,得到了六条结果,我们需要用的是编号 ...

  4. idea查看方法在哪里被调用

    方法一 选中方法名,右键选择Find Usages 方法二 选中方法快捷键ctrl + alt + h查看Hierarchy Callers

  5. LeetCode刷题 树专题

    树专题 关于树的几个基本概念 1 树的节点定义 2 关于二叉树的遍历方法 2.1 前序遍历 2.2 中序遍历 2.3 后序遍历 2.4 层序遍历 3 几种常见的树介绍 3.1 完全二叉树 3.2 二叉 ...

  6. centos7.2安装nginx

    1 安装相关编译环境 yum install gcc-c++ yum install pcre pcre-devel yum install zlib zlib-level yum openssl o ...

  7. Nginx通过ngx_http_limit_req_module实现限制请求数、限速、白名单

    /etc/nginx/limit/white_list:白名单,key-value形式,支持掩码网段 #test 192.168.50.42 0; 192.168.50.0/24 0; /etc/ng ...

  8. LeetCode->链表反转

    这是一个很基础的题目.今天处理了一下,不论是以双指针迭代.递归等方法,都能处理,但是也使这个题目更为典型. 剑指 Offer 24. 反转链表 - 力扣(LeetCode) (leetcode-cn. ...

  9. [hdu7011]被EI加0了

    注意到仅关心于权值大小,预处理出$F_{i}(n)$​​​​表示$a_{1},a_{2},...,a_{n}$​​​​中恰填$i$​​​​​​种不同的数的方案数,那么显然答案即为$\sum_{i=1} ...

  10. [nowcoder5666B]Infinite Tree

    首先考虑由$1!,2!,...,n!$所构成的虚树的一些性质: 1.每一个子树内所包含的阶乘的节点都是一个连续的区间(证明:对于子树k,如果存在$x!$和$y!$,即说明$x!$和$y!$的前$\de ...