Hey, I have just reduced the price for all products. Let's prepare our programming skills for the post-COVID era. Check it out »
Decorator

Decorator in Go

Decorator is a structural pattern that allows adding new behaviors to objects dynamically by placing them inside special wrapper objects.

Using decorators you can wrap objects countless number of times since both target objects and decorators follow the same interface. The resulting object will get a stacking behavior of all wrappers.

Conceptual Example

pizza.go: Component interface

package main

type pizza interface {
	getPrice() int
}

veggieMania.go: Concrete component

package main

type veggeMania struct {
}

func (p *veggeMania) getPrice() int {
	return 15
}

tomatoTopping.go: Concrete decorator

package main

type tomatoTopping struct {
	pizza pizza
}

func (c *tomatoTopping) getPrice() int {
	pizzaPrice := c.pizza.getPrice()
	return pizzaPrice + 7
}

cheeseTopping.go: Concrete decorator

package main

type cheeseTopping struct {
	pizza pizza
}

func (c *cheeseTopping) getPrice() int {
	pizzaPrice := c.pizza.getPrice()
	return pizzaPrice + 10
}

main.go: Client code

package main

import "fmt"

func main() {

	pizza := &veggeMania{}

	//Add cheese topping
	pizzaWithCheese := &cheeseTopping{
		pizza: pizza,
	}

	//Add tomato topping
	pizzaWithCheeseAndTomato := &tomatoTopping{
		pizza: pizzaWithCheese,
	}

	fmt.Printf("Price of veggeMania with tomato and cheese topping is %d\n", pizzaWithCheeseAndTomato.getPrice())
}

output.txt: Execution result


Decorator in Other Languages

Design Patterns: Decorator in Java Design Patterns: Decorator in C# Design Patterns: Decorator in C++ Design Patterns: Decorator in PHP Design Patterns: Decorator in Python Design Patterns: Decorator in Ruby Design Patterns: Decorator in Swift Design Patterns: Decorator in TypeScript