How to Implement the Decorator Pattern in Go

Implement the Decorator Pattern in Go by defining an interface and wrapping concrete components with decorator structs that add behavior.

Implement the Decorator Pattern in Go by defining a common interface, creating a concrete component, and wrapping it with a decorator struct that holds the component and adds behavior.

package main

import "fmt"

type Coffee interface {
    Cost() int
    Description() string
}

type SimpleCoffee struct{}

func (s *SimpleCoffee) Cost() int { return 5 }
func (s *SimpleCoffee) Description() string { return "Simple Coffee" }

type MilkDecorator struct {
    Coffee Coffee
}

func (m *MilkDecorator) Cost() int { return m.Coffee.Cost() + 2 }
func (m *MilkDecorator) Description() string { return m.Coffee.Description() + ", Milk" }

func main() {
    var c Coffee = &SimpleCoffee{}
    c = &MilkDecorator{Coffee: c}
    fmt.Println(c.Description(), c.Cost())
}