python设计模式之责任链

本文介绍了责任链设计模式的概念及其实现方式,通过一个具体的Python示例解释了如何使用责任链来处理请求,使得多个对象有机会处理同一个请求,从而降低了请求发送者与接收者之间的耦合。

python设计模式之责任链

意图

  • 使多个对象都有机会处理请求,从而避免请求的发送则和接受者之间的耦合关系。将这些对象连城一条链,并沿着这条连传递该请求,知道有一个对象处理它为止

适用性

  • 有多个对象可以处理一个请求,哪个对象处理该请求运行时刻决定
  • 想在不明确指定接受者的情况下,向多个对象中的一个提交一个请求

例子

# -*- coding=utf-8 -*-


class Handler(object):
    def successor(self, successor):
        self.successor = successor


class ConcreteHandler1(Handler):
    def handle(self, request):
        if request > 0 and request <= 10:
            print("in handler1")
        else:
            self.successor.handle(request)


class ConcreteHandler2(Handler):
    def handle(self, request):
        if request > 10 and request <= 20:
            print("in handler2")
        else:
            self.successor.handle(request)


class ConcreteHandler3(Handler):
    def handle(self, request):
        if request > 20 and request <= 30:
            print("in handler3")
        else:
            print('end of chain, no handler for {}'.format(request))


if __name__ == "__main__":
    h1 = ConcreteHandler1()
    h2 = ConcreteHandler2()
    h3 = ConcreteHandler3()

    h1.successor(h2)
    h2.successor(h3)

    requests = [2, 5, 14, 22, 18, 3, 35, 27, 20]
    for request in requests:
        h1.handle(request)

#输出
in handler1
in handler1
in handler2
in handler3
in handler2
in handler1
end of chain, no handler for 35
in handler3
in handler2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值