✨ GLEAM ALCHEMY DIFFICULTY: Adept Creational

The Singleton

Global state management through BEAM actors.

✧ GANG OF FOUR LINEAGE & ARCANUM ✧
GOF DESIGN PATTERN: Singleton
ARCANUM SCHOOL: Conjuration // Node Singularity
SCRIBE / ARCHON: Joshua Edward McLaughlin Cox
CANONICAL REGISTRATION:
// GLEAM PATTERN //
import gleam/erlang/process.{type Subject}
import gleam/otp/actor

pub type Message {
  GetMana(reply_to: Subject(Int))
  UseMana(amount: Int)
}

fn handle_message(message: Message, mana: Int) -> actor.Next(Message, Int) {
  case message {
    GetMana(client) -> {
      process.send(client, mana)
      actor.continue(mana)
    }
    UseMana(amount) -> {
      actor.continue(mana - amount)
    }
  }
}

pub fn start_ley_line() -> Result(Subject(Message), actor.StartError) {
  actor.start(1000, handle_message)
}

The Singleton

True Singletons on the BEAM are named processes or actors. We eschew global mutable state in favor of a message-passing ley line entity.

Runic Tags: #conjuration #singleton #gleam #otp