【编程思想】【设计模式】【行为模式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) 职责链模式是一种行为模式,为解除请求的发送者和接收者之间的耦合,而使多个对象都有机会处理这个请求.将这些对象连接成一条链,并沿着 ...
随机推荐
- topk算法
方法一 堆排序 自建堆 heapMax方法,从上至下调整堆 pop时,可以使用自上而下调整堆,调用heapMax(arr,0,sz-1); push时,需要自下到上调整即 从上到下调整: void h ...
- vue禁用浏览器回退
解决方案 mounted() { history.pushState(null, null, document.URL) window.addEventListener('popstate', () ...
- Mysql - 如何存储 10位、13位的 unix 时间戳?
背景 前面有讲过存日期时间可以用 datetime.timestamp 类型:https://www.cnblogs.com/poloyy/p/15546735.html 格式是: YYYY-MM- ...
- 《Python语言程序设计》【第2周】Python基本图形绘制
实例2:Python蟒蛇绘制 #PythonDraw.py import turtle #import 引入了一个绘图库 turtle 海龟库--最小单位像素 turtle.setup(650, 35 ...
- IIS设置URL重写,实现页面的跳转的重定向方法
默认IIS是不提供URL重写模块的. 请注意,不要将IIS默认的HTTP重定向理解为url重写. 安装url重写模块 url重写,是要从iis的应用市场下载url重写组件才可以的. URL重写工具的下 ...
- 彻底搞懂Spring状态机原理,实现订单与物流解耦
本文节选自<设计模式就该这样学> 1 状态模式的UML类图 状态模式的UML类图如下图所示. 2 使用状态模式实现登录状态自由切换 当我们在社区阅读文章时,如果觉得文章写得很好,我们就会评 ...
- 如何将rabbitmq集群中的某个节点移除.
首先将要移除的节点停机. root@rabbitmq-03:~# rabbitmqctl stop Stopping and halting node 'rabbit@rabbitmq-03' ... ...
- dart系列之:dart中的异步编程
目录 简介 为什么要用异步编程 怎么使用 Future 异步异常处理 在同步函数中调用异步函数 总结 简介 熟悉javascript的朋友应该知道,在ES6中引入了await和async的语法,可以方 ...
- ICCV 2021口罩人物身份鉴别全球挑战赛冠军方案分享
1. 引言 10月11-17日,万众期待的国际计算机视觉大会 ICCV 2021 (International Conference on Computer Vision) 在线上如期举行,受到全球计 ...
- 数字逻辑实践4->面向硬件电路的设计思维--FPGA设计总述
本文是对实验课上讲解的"面向硬件电路的设计思维"的总结,结合数字逻辑课本,进行提炼和整理. 主要来源是课件与本人整理,部分参考了网络大佬的博客. 本文主要介绍不同于之前软件设计思维 ...