2

Sorry for the long-winded examples, but I've run into this type of software design problem recently, and have been thinking about it. Not sure if there's a term for it, so I'll give 2 general examples to give an idea:

Ex 1: You're working on an RPG game, and you have a class for the main character. That character's reactions to the game world changes based on what you're wearing/holding, skills allotted, basically your object's internal state.

Say you have the following items in the game:

  • Ring of regeneration: allows your character to regenerate health over time
  • Sneaky sneakers: increases sneak
  • Magic mirror: reflects % of incoming damage
  • Doofy glasses: highlights crafting resources

Ex 2: You have a Toyota Corolla. There are different configurations of it, but they're all Toyota Corollas. ABS, and Traction Control are optional features (behaviors) you can add to the baseline model.

  • The baseline model does nothing extra when running.
  • With ABS, the car checks and responds for sudden stops when the car's running
  • With Traction Control, the car checks and responds to loss of traction when the car's running
  • And obviously, when you have a car with both, you'll do both behaviors when the car's running.

Common properties of the two examples:

  • the class of importance has a concrete blank slate that it can start with
  • optional items/parts can add an ability or extra behavior to that object; something extra to do per game tick/while running
  • may or may not mutate the object when item/behavior is added or taken off of it (increment sneak when putting on sneakers, decrement it when taking it off)

Potential solutions (but not adequate):

if statements:

if ch.isWearing 'doofy glasses':
    render with doofy shader
else if ch.isWearing ...

Doesn't work. Need to add a clause for every part. Class can get big and complicated very fast.

Strategy pattern:

class TractionControlStrategy
class ABSstrategy

class Toyota:
    TractionControlStrategy tcs
    ABSstrategy abs
    run():
        if tcs not null:
            tcs.run()
        if abs not null:
            abs.run()

carWithTCS = new Toyota(new TractionControlStrategy())

Not much better than the previous solution as you still have the long list of if statements

Strategy with subclasses:

class Toyota:
    run():
        // does nothing

class ToyotaWithABS : Toyota
    ABSstrategy abs = new ABSstrategy()
    run():
        abs.run

class ToyotaWithTCS : Toyota ...

Satisfies the Open/Closed Principle I think. Better than the previous one maybe? But now you'll have to create a class for every combination of configurations. If you found out later on that there's other optional features, then the number of classes would double for every feature you need to implement...

How can these types of interactions and behaviors be modeled with OOP? What design patterns, or combinations of design patterns promote this kind of thing?

Really not sure if this is a good question or if I'm clear with what I'm asking as I've never really practiced good software design.

I'm learning OpenGL, working on my 3D mesh/model class. This question is related because in my renderer, indexing and textures are optional for a mesh. So a mesh can be vertices only, indexed vertices, vertices and textures, or all 3. Plus, I can't foresee what features I may want to add in the future as I don't know what I'll be learning like a month down the line, so I need the class to be flexible, and extensible

2 Answers 2

1

You are right and any option where you need to describe all possible combinations (whether via switch/if or via class hierarchy) is not good.

One way is to use the decorator pattern to wrap your main class and add dynamic properties. Or you can have separate Stats class as an filed in the main class and decorate it with additional items.

class Thing

    BasicStats stats

    constructor() 
        this->stats = new BasicStats()

    addItem(Item item)
        // Decorate current stats with new stats
        item->setComponent(this->stats)
        this->stats = item
        return this

    int getHealth()
        return this->stats->getHealth()

You can use it like this:

 thing = new Thing() // has basic stats
 thing->addItem(new MagicMirror)->addItem(new SilverBullet)
 // will go through the chain of decorators to get the value
 health = thing->getHealth()

Another way is to have a list of dynamic options (or items) in your main class:

class Thing

    Stats stats
    ItemList items

    updateStats() 
        for item in this->items
            item->updateStats(this->stats)
            // OR if we want to not disclose the stats to items
            //    we can pass this and items should use 
            //    character's methods to change stats
            item->updateStats(this)

    add(Item item)
        this->items->append(item)
        return this

Which can be used like this:

thing = new Thing()
thing->add(new MagicMirror())->add(new RingOfRegeneration)->updateStats()

Memento can also be useful if you don't want do change the character stats directly. For example, if you have some "compare" feature where the user (or player) can combine different sets of items to see the impact and then "apply" them.

Also look at the chain-of-responsibility, similar to the option with list of stats - you can create a chain of "Items" and request the stat from this chain. Like you can start with passing the base health value which will be then transformed by each item and you'll get the "upgraded" value at the end of chain.

Update: one more idea, visitor can be useful too:

# Base class for stats, Element
class Stat

   abstract accept(StatVisitor visitor)

class Health extends Stat

   private int health

   accept(StatVisitor visitor)
       # or you can have visitor->visitHealth(this)
       visitor->visit(this)

   multiply(int mult)
      this->health = this->health * mult

class Strength extends Stat     

   private int strength

   accept(StatVisitor visitor)
       visitor->visit(this)

   add(int strength)
      this->strength = this->strength + strength

Stats are "Elements" of the Visitor pattern. The Thing class represents "Client":

# Thing contains stats, this is Client
class Thing

   StatsList stats

   accept(StatsVisitor visitor)
      for stat in this->stats
          stat->visit(visitor)

And "Visitors" are our items, which can modify stats:

# Base visitor class
class StatVisitor

   abstract visit(Health health)
   abstract visit(Strength strength)

class MagicMirror

   # magic mirror multiplies health by 10
   visit(Health health)
      health->multiply(10)

   # magic mirror increases strength +5
   visit(Strength strength)
      strength->add(5)

Now you can do this:

thing = new Thing()
item = MagicMirror()
# now update all the stats with MagicMirror
thing->accept(item)
0

Don't overcomplicate things:

  1. Ring of regeneration: allows your character to regenerate health over time

    This really shouldn't modify your object at all. E.g. putting the ring on may add a timer that tries to increase an entities health (i.e. the wearer's) and taking the ring off removes this timer again.

  2. Sneaky sneakers: increases sneak

    This can be modelled as a modification on a stats:

    class Entity
    
        Map<Skill, SortedList<Modifier>> skillModifiers
    
        getSneakChance()
            sneakChance = .. // compute base value from attributes
            for each mod in skillModifiers[SneakChance]
                sneakChance = mod.apply(sneakChance)
            return sneakChance
    

    The map avoids two drawbacks of decorator and chain-of-responsibility: not every modifier adds another indirection to the evaluation and you can have simpler, value based modifiers (increase a value by x%) as opposed of pushing the logic of what stat/skill is to be modified or how to access it into the modifier also.

    One difficulty is deciding in what order to apply the modifiers: should you first add 20 to your attack damage and then increase it by 5% or the other way around, loosing the 1 damage point? Should certain modifiers apply to the base value only, i.e. do you need passing both the accumulated and the base value in mod.apply?

  3. Magic mirror: reflects % of incoming damage

    Same as for 2. This time map modifiers and reactions onto specific events (i.e. taking damage). This allows for the same effect being applied to multiple entities like an aura or some other aoe spell.

  4. Doofy glasses: highlights crafting resources

    This is again something that doesn't affect the entity. The gui-controller requires this kind of information, so simply query the player for visual modifiers (unless every entity in your game needs to manipulate the behaviour and look of your gui).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.