Golang — Chain of Responsibility Pattern

Matthias Bruns
3 min readMar 17, 2023

The Chain of Responsibility pattern is a behavioral design pattern that allows an object to pass a request along a chain of handlers until one of the handlers can handle the request. This pattern is useful when there are multiple objects that can handle a request, but we do not know which object can handle the request until runtime.

The Gang of Four, in their book “Design Patterns: Elements of Reusable Object-Oriented Software”, first introduced the Chain of Responsibility pattern.

Implementation in Golang

Let’s implement the Chain of Responsibility pattern in Golang. We will use a realistic example where a customer’s order is handled by different departments in a company.

type Order struct {
// ...
}

type OrderHandler interface {
SetNext(OrderHandler) OrderHandler
Handle(*Order) error
}

type OrderProcessor struct {
handler OrderHandler
}

func (o *OrderProcessor) SetHandler(handler OrderHandler) {
o.handler = handler
}

func (o *OrderProcessor) Process(order *Order) error {
return o.handler.Handle(order)
}

type WarehouseHandler struct {
next OrderHandler
}

func (w *WarehouseHandler) SetNext(next OrderHandler) OrderHandler {
w.next = next
return next
}

func (w *WarehouseHandler) Handle(order *Order) error {
if order.WarehouseFilled {…

--

--

Matthias Bruns

Senior Freelancer & Technical Lead Working as a Golang developer since 2020. as a mobile developer since 2013. Focussed on architecture & testability.