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调用测试

相关推荐
CV工程师丁Sir31 分钟前
ArkWeb 手记 04|DevTools 调试与缓存清理
java·spring·缓存·harmonyos
光依旧7 小时前
MCP实战手记系列(十):MCP Server高可用实战
spring boot·高可用·nginx负载均衡·redis哨兵·mcp·微服务容错·resilience4j熔断
Sarvartha7 小时前
final 关键字
java·开发语言
2601_952047797 小时前
单一策略深度教程:用轻易云把集成任务的报错实时推送到钉钉机器人
java·机器人·钉钉
Joy T7 小时前
Spring AI 项目中的 pom.xml、application.yml 与 Nacos:从依赖管理到运行配置
spring·nacos·pom.xml·profile·参数配置·application.yml
数据狐(Datafox)8 小时前
淘宝图片搜索 API 落地实战:基于以图搜货搭建跨境电商选品系统
java·大数据·微服务
Escalating_xu10 小时前
【C 语言】数据在内存中的存储:补码、大小端、整型陷阱与 IEEE 754 全解析
java·c语言·网络
灯澜忆梦10 小时前
【面向对象编程C++】| 基础语法
java·c++·算法