如果一个对象有很多的行为,如果不用恰当的模式,这些行为就只好使用多重的条件选择语句来实现,这样会显得代码逻辑很臃肿,那么有没有方式去消除这种逻辑呢?答案当然是有,那就是使用策略模式
接下来我们演示一下根据传入的不同参数执行不同的计算功能:
- 如果传入的是PLUS,执行数据a+b计算;
- 如果传入的是MINUS,执行数据a-b计算;
- 如果传入的是MULTIPLY,执行数据a*b计算;
- 否则执行数据a/b计算。
public class StrategyDemo {
public static void main(String[] args) {
Integer result = count(3, 5, "MULTIPLY");
System.out.println(result);
}
public static Integer count(Integer a, Integer b, String opt) {
if ("PLUS".equals(opt)) {
return a + b;
} else if ("MINUS".equals(opt)){
return a - b;
} else if ("MULTIPLY".equals(opt)) {
return a * b;
} else {
return a / b;
}
}
}
public interface ArithmeticOperation {
/**
* 计算
*
* @param a 待计算值
* @param b 待计算值
* @return 计算结果
*/
int calculate(int a, int b);
}
public enum ArithmeticEnum implements ArithmeticOperation{
/**
* 加
*/
PLUS {
@Override
public int calculate(int a, int b) {
return a + b;
}
},
/**
* 减
*/
MINUS {
@Override
public int calculate(int a, int b) {
return a - b;
}
},
/**
* 乘
*/
MULTIPLY {
@Override
public int calculate(int a, int b) {
return a * b;
}
},
/**
* 除
*/
DIVIDE {
@Override
public int calculate(int a, int b) {
return a / b;
}
};
}
使用
public class StrategyDemo {
public static void main(String[] args) {
Integer result = count(3, 5, "MULTIPLY");
System.out.println(result);
}
public static Integer count(Integer a, Integer b, String opt) {
ArithmeticEnum arithmeticEnum = ArithmeticEnum.valueOf(opt);
return arithmeticEnum.calculate(a, b);
}
}
原文地址:https://blog.csdn.net/qq_44936392/article/details/134729029
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_41546.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!