Member-only story

Practical Design Pattern in Go: Adapter

A design pattern that allows objects with incompatible interfaces to collaborate.

Jose Sitanggang
6 min readOct 29, 2023
Image by Refactoring.Guru
Image by Refactoring.Guru

The Adapter Pattern is a structural design pattern that allows objects with incompatible interfaces to collaborate. Let me clarify something: an interface does not always mean the type Something interface, but in this context, it is more likely to refer to the contract between types.

I am not sponsored by Refactoring.Guru, but I definitely recommend that you buy the “ DESIGN PATTERNS “ book. It covers all known design patterns in depth and provides easy and simple explanations. This post only covers practical examples of each pattern in a real-world Golang application.

In real word application, we will be often we found case where two or more interface is not compatible, but we want it collaborate together to solve our problem. Let me show you an example:

// HealthHandler is a handler for health check.
type HealthHandler struct {}

// NewHealthHandler creates a new health handler.
func NewHealthHandler() *HealthHandler {
return &HealthHandler{}
}

// ServeHTTP implements http.Handler.
func (h *HealthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
started := time.Now()
l := slog.Default().With("method", r.Method, "uri", r.RequestURI)…

--

--

No responses yet