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

相关推荐
小马爱打代码10 分钟前
Spring Boot 3.4 :@Fallback 注解 - 让微服务容错更简单
spring boot·后端·微服务
旷世奇才李先生32 分钟前
奇哥面试记:SpringBoot整合RabbitMQ与高级特性,一不小心吊打面试官
spring boot·面试·java-rabbitmq
yngsqq38 分钟前
netdxf—— CAD c#二次开发之(netDxf 处理 DXF 文件)
java·前端·c#
A了LONE1 小时前
h5的底部导航栏模板
java·前端·javascript
经典19921 小时前
spring boot 详解以及原理
java·spring boot·后端
星光54221 小时前
飞算JavaAI:给Java开发装上“智能引擎”的超级助手
java·开发语言
学习3人组2 小时前
JVM GC长暂停问题排查
java
R_AirMan2 小时前
深入浅出Redis:一文掌握Redis底层数据结构与实现原理
java·数据结构·数据库·redis
人生在勤,不索何获-白大侠2 小时前
day17——Java集合进阶(Collections、Map)
java·开发语言
程序员小羊!2 小时前
Java教程:JavaWeb ---MySQL高级
java·开发语言·mysql