Design Pattern-Behavioral-Chain of Responsibility Pattern

Chain of Responsibility Model

Overview

  • Allows multiple objects to have the opportunity to process the request, thereby avoiding the coupling between the sender and receiver of the request. These objects are connected into a chain, and the request is passed along this chain until an object handles it

Object

  • Abstract handler (Handler)
  • Concrete handler (ConcreteHandler)
  • Client

Applicable scene

  • There are multiple objects that can handle a request, and which object handles is determined by the runtime
  • Submit a request to one of multiple objects without knowing the recipient

example

# 假设你需要进行请假,每一级主管都有自己的权限,项目主管三天以内,部门经理5天以内,总经理十天以内
from abc import ABCMeta, abstractmethod

class Handler(metaclass=ABCMeta):
    @abstractmethod
    def handle_leave(self):
        pass

class GeneralManager(Handler):
    def handle_leave(self, day):
        if day <= 10:
            print(f"总经理准假{day}天")
            return
        print("你还是辞职吧")
        return

class DeparmentManager(Handler):

    def __init__(self):
        self.next = GeneralManager()

    def handle_leave(self, day):
        if day <= 5:
            print(f"总经理准假{day}天")
            return
        print("部门经理职权不足")
        return self.next.handle_leave(day)

class ProjectManager(Handler):

    def __init__(self):
        self.next = DeparmentManager()

    def handle_leave(self, day):
        if day <= 3:
            print(f"项目主管准假{day}天")
            return
        print("项目主管职权不足")
        return self.next.handle_leave(day)

day = 11
project_manager = ProjectManager()
project_manager.handle_leave(day)

advantage

  • Reduce the degree of coupling, an object does not need to know which other object processed its request

Guess you like

Origin blog.csdn.net/DALAOS/article/details/113882519