Go Notebook
  • Introduction
  • Syntax Helpers
    • Append
    • String
    • Slice
  • Idioms
    • Custom JSON Marshaling
    • Functional Options
    • Type Embedding
    • Laws of Reflection
  • Design Patterns
    • Builder
    • Factory Method
    • Object Pool
    • Singleton
    • Observer
    • Strategy
  • Hello World
    • Getting Started With Go
    • Go Packages
    • Hello World
  • Tic Tac Toe
    • Go Interfaces
    • Go Error Handling
    • Tic Tac Toe
  • HTTP Server
    • HTTP Handler
    • Build a Calculator
    • HTTP Unit Test
  • Concurrency
    • Goroutines
    • Go Concurrency Part 1
    • Go Concurrency Part 2
  • WebSocket Server
    • WebSocket Handler
    • Build a Chatroom
  • User Authentication
    • Go Module
    • Popular Web Libraries
    • React Tools
    • Build an Authentication Server
  • Numerical Computing
    • Gonum
    • Neural Networks
Powered by GitBook
On this page
  1. Design Patterns

Strategy

Strategy pattern also known as policy pattern is a behavioral software design pattern that enables selecting an algorithm at runtime.

The idea is actually very simple. It's probably something you and I have been doing the whole time.

type (
    Engine interface {
        Output() float64
    }

    NaturalAspirated struct {
        // Properties
    }

    Turbocharged struct {
        // Properties
    }
)

func (na NaturalAspirated) Output() float64 {
    // Implementation...
    return power
}

func (tc Turbocharged) Output() float64 {
    // Implementation...
    return power
}

We have two types of engine and they both have different outputs depending on their displacement, torque curves and bunch of other details. We will have a Car object which takes one of these two engines and Drive() in runtime.

type Car struct {
    Engine Engine
}

func (c *Car) Drive() {
    power := c.Engine.Output()

    // Do complex logic with engine power
}
PreviousObserverNextHello World

Last updated 6 years ago