I wrote a program with Java that plays simple music. Currently chords have only one way ('strumming pattern') to be played. I want to expand this and create different 'strumming patterns' that chords can use to play their notes.
The Chord
class has a play()
method that is responsible for playing the chord. Currently it contains the logic for the only 'strumming pattern' of how the notes are played.
To add new strumming patterns, the simplest approach is to change play()
to something like this:
void play(int strummingStyle){
if(strummingStyle == REGULAR_STYLE) playRegular();
if(strummingStyle == SOMETHING_ELSE_STYLE) playSomethingElse();
// .. etc
}
Have a method for each strumming style, and parameterize the method to play a specific style.
However using the Strategy pattern feels like a better approach. What I mean is to encapsulate each strumming pattern in a subclass of StrummingPattern
and set the Chord
to a specific strumming pattern: chord.setStrummingPattern(StrummingPattern pattern);
.
play()
would then simply delegate to the strumming pattern like so:
void play(){
pattern.play();
}
While this clearly feels like the better, more OO approach - I find that I can't explain myself what the actual benefits are. And it's important for me to actually understand why I'm doing something.
Please explain why using the Strategy pattern in a case like this is a better approach than the more naive 'a method represents a behavior' approach. What exactly are the Strategy pattern's benefits in this kind of situation? Why should I use it?