JAVA笔记 | 策略模式+枚举Enum简单实现策略模式(可直接套用)
本篇为更为简单的策略模式应用,使用枚举来进行策略分配
上一篇(链接如下)更像是策略+工厂模式来分配策略
先创建策略相关类
//策略类
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调用测试
原文地址:https://blog.csdn.net/qq_37630282/article/details/144029787
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!