Skip to content

Instantly share code, notes, and snippets.

@sscovil
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sscovil/9557201 to your computer and use it in GitHub Desktop.
Save sscovil/9557201 to your computer and use it in GitHub Desktop.
This gist illustrates implementation of the strategy pattern using an enum.
import org.apache.commons.lang.math.RandomUtils;
import org.testng.Assert;
import org.testng.annotations.Test;
public class enumStrategyPatternTest() {
public enum Strategy {
ADD {
@Override
public int execute(int a, int b) {
return a + b;
}
},
SUBTRACT {
@Override
public int execute(int a, int b) {
return a - b;
}
},
MULTIPLY {
@Override
public int execute(int a, int b) {
return a * b;
}
},
DIVIDE {
@Override
public int execute(int a, int b) {
return a / b;
}
};
public abstract int execute(int a, int b);
}
@Test
public void strategyPatternWorksWithEnum() {
int a = RandomUtils.nextInt();
int b = RandomUtils.nextInt();
Assert.assertTrue(Strategy.ADD.execute(a, b) == a + b);
Assert.assertTrue(Strategy.SUBTRACT.execute(a, b) == a - b);
Assert.assertTrue(Strategy.MULTIPLY.execute(a, b) == a * b);
Assert.assertTrue(Strategy.DIVIDE.execute(a, b) == a / b);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment