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

相关推荐
阿俊-全栈开发3 小时前
LikeShop 单商户SaaS商城分销模块二开:佣金计算与结算逻辑实现
java·开发语言·微服务·likeshop·likeshop开源商城·likeshop多商户
wuminyu6 小时前
C++协程实现接收端的零拷贝Buffer管理原理剖析
java·linux·c语言·jvm·c++
Zhou1411368 小时前
SpringBoot_03_Web开发
前端·spring boot·python
蜗牛互联网8 小时前
WSL Containers GA:本地AI容器的生命周期、网络与治理验收
java·网络·人工智能·后端
CarIise8 小时前
MyBatis动态SQL:从条件拼接到底层原理实战
mybatis
龙亘川9 小时前
铭记英烈守初心,数字强基促服务:亘川智城退役军人服务系统的实践与价值
java·数据库·人工智能
OxYGC9 小时前
[AI工程] Spring AI 第廿一篇:存量 REST 接口的 MCP 化改造实录——工具从哪条路径注册、参数描述怎么写、身份怎么过去
java·人工智能·spring
Zhou1411369 小时前
SpringBoot_02_自动配置原理
java·spring boot·后端
FYKJ_20109 小时前
SSM校园失物招领系统41452-计算机课程设计、毕业设计
java·vue.js·spring boot·python·mysql·typescript·spark
kv1109 小时前
Android studio国内开发有关
java·数据库·android studio