本篇为更为简单的策略模式应用,使用枚举来进行策略分配
上一篇(链接如下)更像是策略+工厂模式来分配策略
JAVA笔记 | 实际上用到的策略模式(可直接套用)-CSDN博客
先创建策略相关类
//策略类
public interface PetStrategy {
/**
* 执行动作 - 跑RUN
*/
String run(String name);
}
//猫实现类
@Service
public class CatStrategy implements PetStrategy{
@Override
public String run(String name) {
return name + "猫跑了";
}
}
//狗实现类
@Service
public class DogStrategy implements PetStrategy{
@Override
public String run(String name) {
return name + "狗跑了";
}
}
新建策略枚举
@Getter
public enum PetTypeEnum {
DOG("1", "DOG", new DogStrategy()),
CAT("2", "CAT", new CatStrategy());
private String code;
private String type;
private PetStrategy petStrategy;
PetTypeEnum(String code, String type,PetStrategy strategy) {
this.code = code;
this.type = type;
this.petStrategy = strategy;
}
//根据code获得枚举策略类型
public static PetTypeEnum getPetTypeEnum(String code){
PetTypeEnum type = Arrays.stream(PetTypeEnum.values())
.filter(a -> a.code.equals(code))
.findFirst()
.orElse(null);
if(null == type){
throw new IllegalArgumentException("未找到type");
}
return type;
}
}
controller调用测试