✨ ARCANUM RUNE DIFFICULTY: Apprentice Behavioral

The Strategy Hex

Define a family of algorithms, encapsulate each one, and make them interchangeable.

✧ GANG OF FOUR LINEAGE & ARCANUM ✧
GOF DESIGN PATTERN: Strategy
ARCANUM SCHOOL: Divination // Tactical Weaving
SCRIBE / ARCHON: Joshua Edward McLaughlin Cox
CANONICAL REGISTRATION:
// CODEX INCANTATION //
use fmt;

type Strategy = struct {
	execute: *fn(a: int, b: int) int,
};

fn strat_add(a: int, b: int) int = {
	return a + b;
};

fn strat_multiply(a: int, b: int) int = {
	return a * b;
};

type Context = struct {
	strategy: *Strategy,
	execute_strategy: *fn(c: *Context, a: int, b: int) int,
};

fn context_execute(c: *Context, a: int, b: int) int = {
	return c.strategy.execute(a, b);
};

export fn main() void = {
	let add_s = Strategy { execute = &strat_add };
	let mult_s = Strategy { execute = &strat_multiply };
	
	let ctx = Context { strategy = &add_s, execute_strategy = &context_execute };
	fmt::printfln("Addition result: {}", ctx.execute_strategy(&ctx, 3, 4))!;
	
	ctx.strategy = &mult_s;
	fmt::printfln("Multiplication result: {}", ctx.execute_strategy(&ctx, 3, 4))!;
};

Why hardcode a battle plan when the warzone is ever-shifting? The Strategy hex lets you hot-swap the internal algorithms of a construct without disrupting its outer shell.

Runic Tags: #behavioral #strategy #simple-systems-hexes