【编程思想】【设计模式】【行为模式Behavioral】chain
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的更多相关文章
- 面向对象编程思想(前传)--你必须知道的javascript
在写面向对象编程思想-设计模式中的js部分的时候发现很多基础知识不了解的话,是很难真正理解和读懂js面向对象的代码.为此,在这里先快速补上.然后继续我们的面向对象编程思想-设计模式. 什么是鸭子类型 ...
- 面向对象编程思想(前传)--你必须知道的javascript(转载)
原文地址:http://www.cnblogs.com/zhaopei/p/6623460.html阅读目录 什么是鸭子类型 javascript的面向对象 封装 继承 多态 原型 this指向 ...
- Java设计模式(14)责任链模式(Chain of Responsibility模式)
Chain of Responsibility定义:Chain of Responsibility(CoR) 是用一系列类(classes)试图处理一个请求request,这些类之间是一个松散的耦合, ...
- 深入浅出设计模式——职责链模式(Chain of Responsibility Pattern)
模式动机 职责链可以是一条直线.一个环或者一个树形结构,最常见的职责链是直线型,即沿着一条单向的链来传递请求.链上的每一个对象都是请求处理者,职责链模式可以将请求的处理者组织成一条链,并使请求沿着链传 ...
- 设计模式:职责链模式(Chain Of Responsibility)
定 义:使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系.将这些对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止. 结构图: 处理请求类: //抽象处理类 abs ...
- 23种设计模式之责任链模式(Chain of Responsibility Pattern)
责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链.这种模式给予请求的类型,对请求的发送者和接收者进行解耦.这种类型的设计模式属于行为型模式. ...
- 设计模式之笔记--职责链模式(Chain of Responsibility)
职责链模式(Chain of Responsibility) 定义 职责链模式(Chain of Responsibility),使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系 ...
- 【设计模式】行为型05责任链模式(Chain of responsibility Pattern)
学习地址:http://www.runoob.com/design-pattern/chain-of-responsibility-pattern.html demo采用了DEBUG级别举例子,理解起 ...
- C#设计模式:职责链模式(Chain of Responsibility)
一,什么是职责链模式(Chain of Responsibility) 职责链模式是一种行为模式,为解除请求的发送者和接收者之间的耦合,而使多个对象都有机会处理这个请求.将这些对象连接成一条链,并沿着 ...
随机推荐
- 【python】以souhu邮箱为例学习DDT数据驱动测试
前言 DDT(Data-Driven Tests)是针对 unittest 单元测试框架设计的扩展库.允许使用不同的测试数据来运行一个测试用例,并将其展示为多个测试用例.通俗理解为相同的测试脚本使用不 ...
- JMeter跨线程组保持登录(多线程组共享cookie)
使用__setProperty设置全局变量: 1.jmeter中创建一个登录请求,然后执行,察看结果树-->查看返回cookie信息,我的是在Response data中的 Response h ...
- 不可忽视的Dubbo线程池
问题描述 线上突然出现Dubbo超时调用,时间刚好为Consumer端设置的超时时间. 有好几个不同的接口都报超时了 第1次调用超时,第2次(或第3次)重试调用非常快(正常水平) Dubbo调用超时的 ...
- K8S使用NodePort类型Service
1.使用nodetype类型 1.1.第一种类型创建:直接在yaml中标记是nodePort apiVersion: v1 kind: Service metadata: name: nginx-se ...
- [cf1137F]Matches Are Not a Child's Pla
显然compare操作可以通过两次when操作实现,以下仅考虑前两种操作 为了方便,将优先级最高的节点作为根,显然根最后才会被删除 接下来,不断找到剩下的节点中(包括根)优先级最高的节点,将其到其所在 ...
- 面试官又整新活,居然问我for循环用i++和++i哪个效率高?
原创:微信公众号 码农参上,欢迎分享,转载请保留出处. 前几天,一个小伙伴告诉我,他在面试的时候被面试官问了这么一个问题: 在for循环中,到底应该用 i++ 还是 ++i ? 听到这,我感觉这面试官 ...
- Jetpack架构组件学习(2)——ViewModel和Livedata使用
要看本系列其他文章,可访问此链接Jetpack架构学习 | Stars-One的杂货小窝 原文地址:Jetpack架构组件学习(2)--ViewModel和Livedata使用 | Stars-One ...
- 【CSS】水平居中和垂直居中
水平居中和垂直居中 2019-11-12 15:35:37 by冲冲 1.水平居中 (1)父级元素是行内元素,子级元素是行内元素,子级元素水平居中 ① 设置父级元素为块级元素 display:bl ...
- 学Web前端开发,选择培训学校是关键--青岛思途
互联网+的提出,催生了Web前端开发行业更大的就业空间,其行业热度也正呈爆炸式增长.专业人才供不应求导致了从业者薪资的居高不下,一般来说Web前端工程师的年薪可达15w以上,工作3~5年后通常可达到1 ...
- 洛谷 P6199 - [EER1]河童重工(点分治+虚树)
洛谷题面传送门 神仙题. 首先看到这样两棵树的题目,我们肯定会往动态树分治的方向考虑.考虑每次找出 \(T_2\) 的重心进行点分治.然后考虑跨过分治中心的点对之间的连边情况.由于连边边权与两棵树都有 ...