Design Patterns

Notes and exercises for learning design patterns

View the Project on GitHub Claptar/design-patterns

Exercise 3: Broker Chain — Basic Stat System

Goal

Build a basic character stat system using the Broker Chain pattern. This exercise focuses on the three-part core: Query, Broker, and Modifier.


Part A — the three core pieces

Implement:

StatQuery — a mutable object with:

StatBroker — an event bus with:

Character — holds base stats and a broker reference:

Verify the bare character with no modifiers:

broker = StatBroker()
hero = Character("hero", broker)
assert hero.get_attack()  == 10
assert hero.get_defense() == 5

Part B — flat bonus modifier

Add a FlatBonusModifier that adds a fixed integer to one stat of one character:

FlatBonusModifier(broker, character_name="hero", stat="attack", bonus=10)

After registering, hero.get_attack() should return 20.

Multiple FlatBonusModifier instances for the same stat should stack:

FlatBonusModifier(broker, "hero", "attack", 10)
FlatBonusModifier(broker, "hero", "attack",  5)
assert hero.get_attack() == 25

Part C — multiplier modifier and removal

Add a MultiplierModifier that multiplies a stat by a float:

MultiplierModifier(broker, character_name="hero", stat="attack", multiplier=2.0)

Add a remove() method to both modifier classes that unsubscribes them from the broker.

Verify:

sword  = FlatBonusModifier(broker, "hero", "attack", 10)   # attack = 20
berserk = MultiplierModifier(broker, "hero", "attack", 2.0) # attack = 40
assert hero.get_attack() == 40

berserk.remove()
assert hero.get_attack() == 20  # multiplier gone

sword.remove()
assert hero.get_attack() == 10  # back to base

Skeleton

See exercise3.py.


Hints


Exercise 2 · Solution 3 · Exercise 4