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. robot_framewok自动化测试--(5)Screenshot 库

    Screenshot 库 Scrennshot 同样为 Robot Framework 标准类库,我们只将它提供的其它中一个关键字"TakeScreenshot",它用于截取到当前 ...

  2. PTA二叉搜索树的操作集 (30分)

    PTA二叉搜索树的操作集 (30分) 本题要求实现给定二叉搜索树的5种常用操作. 函数接口定义: BinTree Insert( BinTree BST, ElementType X ); BinTr ...

  3. vuex配置token和用户信息

    首先设计的是登录成功后端产生token,前端取出放在Local Storage,便于后面每个请求默认带上这里的token以及取用户相关信息 和main.js同级建store.js文件,代码如下 imp ...

  4. 简单的SQl时间序列生成,每次时间间隔10分钟。

    create table #timeseries(Times datetime not null) go declare @firstdate datetime , @lastdate datetim ...

  5. 《Python语言程序设计》【第2周】Python基本图形绘制

    实例2:Python蟒蛇绘制 #PythonDraw.py import turtle #import 引入了一个绘图库 turtle 海龟库--最小单位像素 turtle.setup(650, 35 ...

  6. [源码解析] PyTorch 分布式(10)------DistributedDataParallel 之 Reducer静态架构

    [源码解析] PyTorch 分布式(10)------DistributedDataParallel之Reducer静态架构 目录 [源码解析] PyTorch 分布式(10)------Distr ...

  7. Vulnhub-Empire: LupinOne题解

    Vulnhub-Empire: LupinOne题解 本靶机为Vulnhub上Empire系列之LupinOne,地址:EMPIRE: LUPINONE 扫描与发现 利用arp-scan命令扫描靶机I ...

  8. Codeforces 1466G - Song of the Sirens(哈希)

    Codeforces 题面传送门 & 洛谷题面传送门 事实证明,有的难度评分不算很高.涉及的知识点不算很难的题目也能出得非常神仙 首先考虑如何暴力求答案.注意到一个文本串 \(T\) 在 \( ...

  9. Codeforces 1396D - Rainbow Rectangles(扫描线+线段树)

    Codeforces 题面传送门 & 洛谷题面传送门 一道鸽了整整一年的题目,上一次提交好像是 2020 年 9 月 13 日来着的(?) 乍一看以为第 2 个提交和第 3 个提交只差了 43 ...

  10. Sums gym100753M

    Sums gym100753M 同余最短路模板,然而这个东西貌似也可以做去年D1T2 首先我们选择一个模数作为基准,然后剩下的这样连边: 对于一个面值为 x 的硬币 ,当前在 u 这个点(感性理解一下 ...