JAVA笔记 | 策略模式+枚举Enum简单实现策略模式(可直接套用)

本篇为更为简单的策略模式应用,使用枚举来进行策略分配

上一篇(链接如下)更像是策略+工厂模式来分配策略

JAVA笔记 | 实际上用到的策略模式(可直接套用)-CSDN博客

先创建策略相关类

java 复制代码
//策略类
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 + "狗跑了";
    }
}

新建策略枚举

java 复制代码
@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调用测试

相关推荐
SL_staff4 分钟前
3周搭完MES系统:JVS低代码+JVS-IoT物联网的实战记录
java·前端·低代码
MacroZheng11 分钟前
斩获20w star!Claude Code最强插件,AI编程必备!
java·人工智能·后端
唐青枫2 小时前
Java Spring WebFlux 实战指南:用 Mono、Flux 和 WebClient 写响应式接口
java·spring
小bo波15 小时前
使用Thread子类创建线程 VS 使用Runnable接口创建线程的区别
java·多线程·thread·并发编程·runnable
SamDeepThinking15 小时前
高并发场景下,CompletableFuture与ForkJoinPool该如何取舍?
java·后端·面试
张不才18 小时前
CPU 100% 了怎么办?Java 性能排障的标准化操作
java·后端
shepherd11120 小时前
吞吐量提升 10 倍:高并发大批量数据处理任务的架构演进与性能调优
java·后端·架构
plainGeekDev1 天前
单例模式 → object 声明
android·java·kotlin
用户298698530141 天前
Java 实现 Word 文档文本与图片提取的方法
java·后端