English

Artykuł · Łańcuch zobowiązań

Łańcuch zobowiązań (Chain of Responsibility): podaj dalej, aż ktoś się zajmie

Wzorzec Łańcuch zobowiązań na przykładzie reklamacji w pierogarni: bot, kierownik zmiany i właścicielka tworzą łańcuch, a reklamacja wędruje, aż trafi do kogoś uprawnionego. Wariant klasyczny i potok middleware, kod w pięciu językach.

Autor · · 12 min czytania

Klient pisze, że pierogi dojechały zimne. Jeśli chodzi o 15 zł i jest zdjęcie, zwrot może zrobić automat. Przy większej kwocie decyduje kierownik zmiany, a przy naprawdę dużej – sama Halina. Łańcuch zobowiązań (ang. Chain of Responsibility) układa takich obsługujących w kolejkę: żądanie wędruje od jednego do drugiego, aż ktoś je przejmie.

3
ogniwa łańcucha – bot, kierownik zmiany, właścicielka
20 zł
limit automatycznego zwrotu – ze zdjęciem
1
punkt wejścia dla nadawcy – pierwsze ogniwo

Problem: jedna funkcja zna całą hierarchię

Obsługa reklamacji zaczęła się od zwykłego if/elif:

complaints_before.py
def handle_complaint(c: Complaint) -> str:
    if c.amount <= 20 and c.has_photo:
        return refund_automatically(c)
    elif c.amount <= 100 and is_shift_manager_on_duty():
        return ask_shift_manager(c)
    elif c.amount <= 100:
        return ask_owner(c)  # copy of the branch below, "temporarily"
    else:
        return ask_owner(c)
    # next request: "add an AI triage step before the bot, but only on weekends"

Funkcja zna wszystkich uczestników procesu, ich limity i kolejność. Każda zmiana – nowy krok weryfikacji, inny próg, triaż przez model AI w weekendy – wymaga edycji tej samej funkcji. Nie da się też złożyć innego łańcucha dla innego kanału (np. reklamacje z aplikacji dostawczej omijają bota), bez kopiowania całości.

Rozwiązanie: obsługujący połączeni w łańcuch

Każdy uczestnik procesu staje się obiektem z metodą handle(complaint) i referencją do następnego ogniwa. Ogniwo sprawdza, czy potrafi obsłużyć żądanie; jeśli tak – obsługuje i kończy, jeśli nie – przekazuje dalej. Kolejność i skład łańcucha ustala kod konfiguracyjny, a nie sami obsługujący.

Diagram: Łańcuch obsługi reklamacji
Diagram: Reklamacja na 340 zł przechodzi przez cały łańcuch
RolaW przykładzieOdpowiedzialność
Obsługujący (Handler)ComplaintHandlerwspólny interfejs i referencja do następnego ogniwa
Konkretny obsługującyAutoRefund, ShiftManager, Ownerdecyduje: obsłużyć czy przekazać
Klientformularz reklamacjiwysyła żądanie do pierwszego ogniwa
Konfiguracjakod budujący łańcuchustala skład i kolejność ogniw

Implementacja w pięciu językach

W C#, TypeScripcie, Javie i Pythonie klasa bazowa trzyma referencję do następnego ogniwa i realizuje logikę „obsłuż albo przekaż”, a podklasy dostarczają tylko warunek i sposób obsługi. Metoda setNext zwraca następne ogniwo, dzięki czemu łańcuch buduje się płynnie. W Go ogniwo to struktura z dwiema funkcjami, a łańcuch składa funkcja Chain.

Łańcuch zobowiązań – reklamacje

Complaints.cs
var chain = new AutoRefund();
chain.SetNext(new ShiftManager()).SetNext(new Owner());

Console.WriteLine(chain.Handle(new Complaint(101, 15m, HasPhoto: true)));  // Bot: refunded 15 PLN
Console.WriteLine(chain.Handle(new Complaint(102, 15m, HasPhoto: false))); // Shift manager approved 15 PLN
Console.WriteLine(chain.Handle(new Complaint(103, 340m, HasPhoto: true))); // Halina will call the customer

public sealed record Complaint(int OrderId, decimal Amount, bool HasPhoto);

public abstract class ComplaintHandler
{
    private ComplaintHandler? _next;

    // Returns the next handler, so the chain can be built fluently.
    public ComplaintHandler SetNext(ComplaintHandler next) => _next = next;

    public string Handle(Complaint c) =>
        CanHandle(c) ? Resolve(c)
        : _next?.Handle(c) ?? $"#{c.OrderId}: nobody could handle the complaint";

    protected abstract bool CanHandle(Complaint c);
    protected abstract string Resolve(Complaint c);
}

public sealed class AutoRefund : ComplaintHandler
{
    protected override bool CanHandle(Complaint c) => c.Amount <= 20m && c.HasPhoto;
    protected override string Resolve(Complaint c) => $"#{c.OrderId}: Bot: refunded {c.Amount} PLN";
}

public sealed class ShiftManager : ComplaintHandler
{
    protected override bool CanHandle(Complaint c) => c.Amount <= 100m;
    protected override string Resolve(Complaint c) => $"#{c.OrderId}: Shift manager approved {c.Amount} PLN";
}

public sealed class Owner : ComplaintHandler
{
    protected override bool CanHandle(Complaint c) => true; // the last link takes everything
    protected override string Resolve(Complaint c) => $"#{c.OrderId}: Halina will call the customer";
}
complaints.ts
type Complaint = { orderId: number; amount: number; hasPhoto: boolean };

abstract class ComplaintHandler {
  private next?: ComplaintHandler;

  /** Returns the next handler, so the chain can be built fluently. */
  setNext(next: ComplaintHandler): ComplaintHandler {
    this.next = next;
    return next;
  }

  handle(c: Complaint): string {
    if (this.canHandle(c)) return this.resolve(c);
    return this.next?.handle(c) ?? `#${c.orderId}: nobody could handle the complaint`;
  }

  protected abstract canHandle(c: Complaint): boolean;
  protected abstract resolve(c: Complaint): string;
}

class AutoRefund extends ComplaintHandler {
  protected canHandle(c: Complaint) { return c.amount <= 20 && c.hasPhoto; }
  protected resolve(c: Complaint) { return `#${c.orderId}: Bot: refunded ${c.amount} PLN`; }
}

class ShiftManager extends ComplaintHandler {
  protected canHandle(c: Complaint) { return c.amount <= 100; }
  protected resolve(c: Complaint) { return `#${c.orderId}: Shift manager approved ${c.amount} PLN`; }
}

class Owner extends ComplaintHandler {
  protected canHandle() { return true; } // the last link takes everything
  protected resolve(c: Complaint) { return `#${c.orderId}: Halina will call the customer`; }
}

const chain = new AutoRefund();
chain.setNext(new ShiftManager()).setNext(new Owner());

console.log(chain.handle({ orderId: 101, amount: 15, hasPhoto: true }));  // Bot: refunded 15 PLN
console.log(chain.handle({ orderId: 102, amount: 15, hasPhoto: false })); // Shift manager approved 15 PLN
console.log(chain.handle({ orderId: 103, amount: 340, hasPhoto: true })); // Halina will call the customer
Complaints.java
record Complaint(int orderId, double amount, boolean hasPhoto) {}

abstract class ComplaintHandler {
    private ComplaintHandler next;

    // Returns the next handler, so the chain can be built fluently.
    ComplaintHandler setNext(ComplaintHandler next) {
        this.next = next;
        return next;
    }

    final String handle(Complaint c) {
        if (canHandle(c)) return resolve(c);
        return next != null ? next.handle(c) : "#" + c.orderId() + ": nobody could handle the complaint";
    }

    protected abstract boolean canHandle(Complaint c);
    protected abstract String resolve(Complaint c);
}

class AutoRefund extends ComplaintHandler {
    protected boolean canHandle(Complaint c) { return c.amount() <= 20 && c.hasPhoto(); }
    protected String resolve(Complaint c) { return "#%d: Bot: refunded %.0f PLN".formatted(c.orderId(), c.amount()); }
}

class ShiftManager extends ComplaintHandler {
    protected boolean canHandle(Complaint c) { return c.amount() <= 100; }
    protected String resolve(Complaint c) { return "#%d: Shift manager approved %.0f PLN".formatted(c.orderId(), c.amount()); }
}

class Owner extends ComplaintHandler {
    protected boolean canHandle(Complaint c) { return true; } // the last link takes everything
    protected String resolve(Complaint c) { return "#%d: Halina will call the customer".formatted(c.orderId()); }
}

public class Complaints {
    public static void main(String[] args) {
        var chain = new AutoRefund();
        chain.setNext(new ShiftManager()).setNext(new Owner());

        System.out.println(chain.handle(new Complaint(101, 15, true)));  // Bot: refunded 15 PLN
        System.out.println(chain.handle(new Complaint(102, 15, false))); // Shift manager approved 15 PLN
        System.out.println(chain.handle(new Complaint(103, 340, true))); // Halina will call the customer
    }
}
complaints.go
package main

import "fmt"

type Complaint struct {
	OrderID  int
	Amount   float64
	HasPhoto bool
}

type Handler interface {
	Handle(c Complaint) string
}

// link is one handler in the chain: it resolves the complaint or passes it on.
type link struct {
	name    string
	can     func(Complaint) bool
	resolve func(Complaint) string
	next    Handler
}

func (l *link) Handle(c Complaint) string {
	if l.can(c) {
		return fmt.Sprintf("#%d: %s: %s", c.OrderID, l.name, l.resolve(c))
	}
	if l.next == nil {
		return fmt.Sprintf("#%d: nobody could handle the complaint", c.OrderID)
	}
	return l.next.Handle(c)
}

// Chain links the handlers in order and returns the first one.
func Chain(links ...*link) Handler {
	for i := 0; i < len(links)-1; i++ {
		links[i].next = links[i+1]
	}
	return links[0]
}

func main() {
	chain := Chain(
		&link{name: "Bot",
			can:     func(c Complaint) bool { return c.Amount <= 20 && c.HasPhoto },
			resolve: func(c Complaint) string { return fmt.Sprintf("refunded %.0f PLN", c.Amount) }},
		&link{name: "Shift manager",
			can:     func(c Complaint) bool { return c.Amount <= 100 },
			resolve: func(c Complaint) string { return fmt.Sprintf("approved %.0f PLN", c.Amount) }},
		&link{name: "Owner",
			can:     func(Complaint) bool { return true }, // the last link takes everything
			resolve: func(Complaint) string { return "Halina will call the customer" }},
	)
	fmt.Println(chain.Handle(Complaint{101, 15, true}))
	fmt.Println(chain.Handle(Complaint{102, 15, false}))
	fmt.Println(chain.Handle(Complaint{103, 340, true}))
}
complaints.py
from __future__ import annotations

from abc import ABC, abstractmethod
from dataclasses import dataclass


@dataclass(frozen=True)
class Complaint:
    order_id: int
    amount: float
    has_photo: bool


class ComplaintHandler(ABC):
    def __init__(self) -> None:
        self._next: ComplaintHandler | None = None

    def set_next(self, handler: ComplaintHandler) -> ComplaintHandler:
        """Returns the next handler, so the chain can be built fluently."""
        self._next = handler
        return handler

    def handle(self, c: Complaint) -> str:
        if self.can_handle(c):
            return self.resolve(c)
        if self._next is None:
            return f"#{c.order_id}: nobody could handle the complaint"
        return self._next.handle(c)

    @abstractmethod
    def can_handle(self, c: Complaint) -> bool: ...

    @abstractmethod
    def resolve(self, c: Complaint) -> str: ...


class AutoRefund(ComplaintHandler):
    def can_handle(self, c): return c.amount <= 20 and c.has_photo
    def resolve(self, c): return f"#{c.order_id}: Bot: refunded {c.amount:.0f} PLN"


class ShiftManager(ComplaintHandler):
    def can_handle(self, c): return c.amount <= 100
    def resolve(self, c): return f"#{c.order_id}: Shift manager approved {c.amount:.0f} PLN"


class Owner(ComplaintHandler):
    def can_handle(self, c): return True  # the last link takes everything
    def resolve(self, c): return f"#{c.order_id}: Halina will call the customer"


chain = AutoRefund()
chain.set_next(ShiftManager()).set_next(Owner())
for complaint in (Complaint(101, 15, True), Complaint(102, 15, False), Complaint(103, 340, True)):
    print(chain.handle(complaint))

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • Krok po kroku
  • Różne łańcuchy z tych samych ogniw
  • Wariant: potok middleware
  • Kiedy stosować, a kiedy nie
  • Powiązania z innymi wzorcami
  • W praktyce
  • Sprawdź się

Załóż darmowe konto · Zaloguj się