Article directory
Preface
Recording JAVA
the Map + 函数式编程
use of encapsulation code can effectively solve many if-else
uses.
1. DineTypeEnum enumeration class
/**
* 吃饭方式枚举
* @Author:lzf
* @Date: 2023-3-16
*/
public enum DineTypeEnum {
/**
* 汉堡
*/
HAMBURG(1,"汉堡"),
/**
* 米饭
*/
RICE(2,"米饭");
private Integer code;
private String type;
DineTypeEnum(Integer code,String type) {
this.code = code;
this.type = type;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
2. Write business classes
Implement the business to be developed here yourself.
/**
* @Author:lzf
* @Date: 2023-3-16
*/
public interface DineService {
String eatHamburger(String message);
String eatRice(String message);
}
/**
* @Author:lzf
* @Date: 2023-3-16
*/
@Service
public class DineServiceImpl implements DineService{
@Override
public String eatHamburger(String message) {
return "汉堡真好吃!"+message;
}
@Override
public String eatRice(String message) {
return "泰国香米!!!!"+message;
}
}
3. Core tools
map
Collections store different implementation methods, and @PostConstruct
annotations can be executed after dependency injection is loaded into the object.
/**
*
* @Author:lzf
* @Date: 2023-3-16
*/
@Component
public class DineTypeService {
@Resource
DineService dineService;
private final Map<Integer, Function<String, String>> map = new HashMap<>();
/**
* @PostConstruct
* 被注解的方法,在对象加载完依赖注入后执行。
* Constructor > @Autowired > @PostConstruct
*/
@PostConstruct
private void init(){
map.put(DineTypeEnum.HAMBURG.getCode(), s -> dineService.eatHamburger(s));
map.put(DineTypeEnum.RICE.getCode(), s -> dineService.eatRice(s));
}
/**
* 获取 函数式map里的数据
* @param type
* @param message
* @return
*/
public String getDate(Integer type,String message){
return map.get(type).apply(message);
}
}
4. Call method
@Resource
DineTypeService dineTypeService;
@Test
void test1(){
System.out.println(dineTypeService.getDate(DineTypeEnum.HAMBURG.getCode(), "-- lalala"));
System.out.println(dineTypeService.getDate(DineTypeEnum.RICE.getCode(), "-- lalala"));
}