banner
Jul 16, 2023
112 Views

Chain of Responsibility pattern

Written by
banner

The chain-of-responsibility pattern is a behavioral design pattern consisting of a source of command objects and a series of processing objects.Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.

Mẫu Chain of Responsibility là một mẫu thiết kế hành vi gồm các đối tượng lệnh và một chuỗi các đối tượng xử lý. Mỗi đối tượng xử lý chứa logic xác định các loại đối tượng lệnh mà nó có thể xử lý; những đối tượng còn lại được chuyển cho đối tượng xử lý tiếp theo trong chuỗi. Cũng tồn tại một cơ chế để thêm các đối tượng xử lý mới vào cuối chuỗi này.

Ví dụ bạn đang làm chức năng mua sắm thiết bị cho công ty. Nếu giá thiết bị dưới 1,000 thì cấp Manager được tự quyết, dưới 5,000 thì cấp Director được quyết và dưới 10,000 thì CEO được duyệt. Cao hơn thì phải họp hội đồng quản trị. Chúng ta sẽ code như sau:

class PurchaseRequest:
    def __init__(self, amount, purpose):
        self.amount = amount
        self.purpose = purpose


class Approver:
    def __init__(self, successor=None):
        self.successor = successor

    def process_request(self, request):
        pass


class Manager(Approver):
    def process_request(self, request):
        if request.amount <= 1000:
            print(f"Manager approves the purchase request for {request.purpose}.")
        elif self.successor is not None:
            self.successor.process_request(request)


class Director(Approver):
    def process_request(self, request):
        if request.amount <= 5000:
            print(f"Director approves the purchase request for {request.purpose}.")
        elif self.successor is not None:
            self.successor.process_request(request)


class CEO(Approver):
    def process_request(self, request):
        if request.amount <= 10000:
            print(f"CEO approves the purchase request for {request.purpose}.")
        else:
            print(f"Purchase request for {request.purpose} requires a board meeting.")


# Client code
purchase_request = PurchaseRequest(800, "Office supplies")

manager = Manager()
director = Director()
ceo = CEO()

manager.successor = director
director.successor = ceo

manager.process_request(purchase_request)

purchase_request = PurchaseRequest(6000, "New equipment")
manager.process_request(purchase_request)

purchase_request = PurchaseRequest(15000, "Company retreat")
manager.process_request(purchase_request)
Article Categories:
dev
banner

Leave a Reply

Your email address will not be published. Required fields are marked *