Last active
August 29, 2015 13:57
-
-
Save sscovil/9557201 to your computer and use it in GitHub Desktop.
This gist illustrates implementation of the strategy pattern using an enum.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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