What pattern to use for this ‘constructor’? Decorator vs Factory?

  softwareengineering

I’m developing a program to generate LARP characters in java and I’ve hit a snag.

Initially I had planned to use a decorator to iterate through the potential ‘roles’ (effectively classes), and then from that work out the costs for each skill depending on the combination of roles and store that in the character. I.e you might be a Java Coder/Nerdfighter, if those are your two roles, or you might just have the SysAdmin role etc.

I then prototyped out a way to buy a skill that required looking up skills in a data base that contained their name and cost. Here is the snag: If I’ve preworked out the costs then I don’t ever need to look up the database, so no changes in the db are pushed through (if the skill costs on a SysAdmin go down I’d like to know). As well as this, I may only buy a fraction of the available skills so I’ll be storing unnecessary data on skill costs, and besides the character should only know about their skills, not all skills. More over, the decorator would only decorate the skill costs, nothing more.

Instead I feel I need a factory that has two options for constructing the character, something like:

public static CharacterFactory multiRolePlayerCharacter(Role firstRole, Role secondRole) {
    /*Some code goes here*/
}
public static CharacterFactory singleRolePlayerCharacter(Role role) {
    /*Some more code goes here*/    
}

But this seems far less extensible compared to the decorator. If the game ever changes so that you can multirole morethan twice (and Java Coder/Nerdfighter/SysAdmin is an allowed role) then I need to rework from the top to add a new factory in. Also I don’t quite know how each factory differs besides perhaps a flag to say if it’s multirole or not, and another variable to hold the secondRole. Which doesn’t seem much.

So it seems either way I lose: Decorator adds extensibility for the long run whilst bogging my classes/objects down, and Factory will work to start with but will resist change.

So how do I know which one to pick? Is there some way to combine the two?

11

You need a Character class that can hold a list of roles. Add roles to the constructor (or whereever) using an array, so you’re never limited. You might even have an addRole method so you can add roles later. (And remove them? An aging Warrior might think seriously about becoming a Wizard, or even an Accountant. Those swords get heavy when you’re older.) (Trivia note: this is sometimes called “Dependency Injection”.)

Handling a list of arbitrary length is a bit more difficult than handling just one item, but you know you have to do it. Sometimes, there’s really only three numbers, “zero”, “one”, and “many”. “Two” is really just “many”.

1

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website Kho Theme wordpress Kho Theme WP Theme WP

LEAVE A COMMENT