The Singleton Core Crystal
Implement the Singleton pattern in Move by storing a single resource at a module address.
✧ GANG OF FOUR LINEAGE & ARCANUM ✧
GOF DESIGN PATTERN: Singleton
ARCANUM SCHOOL: Abjuration // Warding
SCRIBE / ARCHON: Joshua Edward McLaughlin Cox
CANONICAL REGISTRATION:
// CODEX INCANTATION //
module arcane::singleton {
use std::signer;
struct CoreCrystal has key {
energy: u64,
}
const EALREADY_INITIALIZED: u64 = 1;
const ENOT_AUTHORIZED: u64 = 2;
public fun initialize(account: &signer) {
let addr = signer::address_of(account);
assert!(addr == @arcane, ENOT_AUTHORIZED);
assert!(!exists<CoreCrystal>(addr), EALREADY_INITIALIZED);
move_to(account, CoreCrystal { energy: 1000 });
}
public fun consume_energy(addr: address, amount: u64) acquires CoreCrystal {
let crystal = borrow_global_mut<CoreCrystal>(addr);
crystal.energy = crystal.energy - amount;
}
}
Runic Tags:
#creational
#singleton
#move
#crystal