使用Enum实现枚举代码更为清晰和简单,适合于处理一些比较简单的业务流程。如果算法或者业务流程比较复杂,还是使用以前的吧。直接贴代码吧,同样是上篇文章中的例子。
- public enum TestStrategy {
- RepTempRuleOne{
- @Override
- public String replace(String oldString) {
- // TODO Auto-generated method stub
- String newString=oldString.replaceFirst("a", "XXX");
- return newString ;
- }
- },
- RepTempRuleTwo{
- @Override
- public String replace(String oldString) {
- // TODO Auto-generated method stub
- String newString=oldString.replaceFirst("n", "***");
- return newString ;
- }
- };
- abstract String replace(String oldString);
- public static void main(String... args){
- String oldString= "www.zuiniuwang.com";
- RepTempRuleSolveEnum repTempRuleSolve=new RepTempRuleSolveEnum(TestStrategy.RepTempRuleOne);
- String myNewString = repTempRuleSolve.getNewContext(oldString);
- System.out.println("newString is "+myNewString);
- repTempRuleSolve.changeAlgorithm(TestStrategy.RepTempRuleTwo);
- myNewString = repTempRuleSolve.getNewContext(oldString);
- System.out.println("Second New String is "+myNewString);
- }
- }
- class RepTempRuleSolveEnum {
- private TestStrategy strategy;
- public RepTempRuleSolveEnum(TestStrategy rule){
- this.strategy=rule ;
- }
- public String getNewContext(String oldString) {
- try {
- return strategy.replace(oldString);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null ;
- }
- public void changeAlgorithm(TestStrategy newAlgorithm) {
- strategy = newAlgorithm;
- }
本文转自 最牛傻蛋 51CTO博客,原文链接:http://blog.51cto.com/zuiniuwang/718357,如需转载请自行联系原作者