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

Singleton

This one is pretty common and straightforward.

Singleton creational design pattern restricts the instantiation of a type to a single object.

Previously I built an army, now I wish to have a general that will lead my army. I just want one general because I don't want a mutiny.

package army

var (
    once sync.Once
    commander *General
)

// Outside of this package, no one can access this struct except through NewGeneral()
type general struct {
    Army Army
}

func NewGeneral(armySize int) *general {
    once.Do(func() {
        commander = &general{Army: New(armySize)}
    })

    return commander
}
PreviousObject PoolNextObserver

Last updated 6 years ago