推荐学习网站: www.mayikt.com
三、策略模式+自定义函数接口另一种写法
函数接口的入参是多个,返回值是一个
使用场景: 使用策略模式实现计算器功能
3.1 创建策略和实现类
/**
* <h1>Operation接口,用于逻辑的计算</h1>
*
* @author zx
* @date 2022年04月13日 8:36
*/
public interface Operation {
/**
* 计算两个值
*
* @param a 数字A
* @param b 数字B
* @return 另个计算结果
*/
int execute(int a, int b);
}
/**
* <h1>加法运算</h1>
*
* @author zx
* @date 2022年04月13日 8:36
*/
public class AddOperation implements Operation {
@Override
public int execute(int a, int b) {
return a + b;
}
}
/**
* <h1>除法运算</h1>
*/
public class DivOperation implements Operation {
@Override
public int execute(int a, int b) {
return a / b;
}
}
/**
* <h1>乘法运算</h1>
*/
public class MultiOperation implements Operation {
@Override
public int execute(int a, int b) {
return a * b;
}
}
/**
* <h1>减法运算</h1>
*/
public class SubOperation implements Operation {
@Override
public int execute(int a, int b) {
return a - b;
}
}
3.2 自定义函数接口
/**
* 自定义的函数接口
*
* @author zx
* @date 2022年04月13日 8:46
*/
@FunctionalInterface
public interface OperationFunction<T, V, R> {
R apply(T t, V v);
}
3.3 构建关系
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* @author zx
* @date 2022年04月13日 8:42
*/
public class OperationContext {
//使用自定义的函数接口来构建他们的关系.
//实际开发中使用 @PostConstruck
private static Map<String, OperationFunction<Integer, Integer, Integer>> map = new HashMap<>();
static {
map.put("add", (a, b) -> new AddOperation().execute(a, b));
map.put("sub", (a, b) -> new SubOperation().execute(a, b));
map.put("multi", (a, b) -> new MultiOperation().execute(a, b));
map.put("div", (a, b) -> new DivOperation().execute(a, b));
}
public Integer getOperationResult(String type, Integer a, Integer b) {
OperationFunction<Integer, Integer, Integer> operationFunction = map.get(type);
if (Objects.nonNull(operationFunction)) {
return operationFunction.apply(a, b);
}
throw new RuntimeException("type=" + type + "类型错误");
}
}
3.4 测试类
/**
* @author zx
* @date 2022年04月13日 9:06
*/
public class MainTest {
public static void main(String[] args) {
OperationContext context = new OperationContext();
Integer add = context.getOperationResult("add", 12, 23);
System.out.println("add result:"+add);
Integer sub = context.getOperationResult("sub", 12, 23);
System.out.println("sub result:"+sub);
Integer multi = context.getOperationResult("multi", 12, 23);
System.out.println("multi result:"+multi);
Integer div = context.getOperationResult("div", 12, 23);
System.out.println("div result:"+div);
Integer other= context.getOperationResult("xxxx", 12, 32);
}
}
其他方式后续陆续更新。可以先提供一个思路,比如: 规则抽象画的一种规则模板引擎方式、还有结合spring特性的ApplicationContextWare 进行构建,和一个接口多个实现,spring会自动注入到一个map中特性来构建策略的关系.可以先试着实现一下。