策略模式实践

目录

前言

五个部分

名词解释

代码

controller层

HelloService接口

实现类

自定义注解

上下文

策略工厂

[Java SPI配置](#Java SPI配置)

验证


前言

五个部分

接口、实现类、自定义注解、上下文、策略工厂

名词解释

自定义注解(方便后期增加实现类后灵活控制策略)

上下文(初始化接口,进行数据承接)

策略工厂(利用java SPI使接口与实现解耦,并通过验证注解是否存在,调用不同的策略)

代码

controller层

java 复制代码
package com.zsp.sheji.JavaSPI;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("hello")
public class HelloController {

    @PostMapping("/pay")
    public String pay(){
        PayContext payContext = new PayContext();
        payContext.setHelloService(PayFactory.makeHello("helloOne"));
        String result = payContext.sayHello("你好");
        return result;
    }
}

HelloService接口

java 复制代码
package com.zsp.sheji.JavaSPI;

public interface HelloService {
    String sayHello(String hello);
}

实现类

这里写了两个实现类,模拟真实环境中的不同策略调用

HelloOneServiceImpl

java 复制代码
package com.zsp.sheji.JavaSPI;

import org.springframework.stereotype.Service;

@Pay(type = "helloOne")
@Service
public class HelloOneServiceImpl implements HelloService{
    @Override
    public String sayHello(String hello) {
       return  hello + "=== one";
    }
}

HelloTwoServiceImpl

java 复制代码
package com.zsp.sheji.JavaSPI;

import org.springframework.stereotype.Service;

@Pay(type = "helloTwo")
@Service
public class HelloTwoServiceImpl implements HelloService{
    @Override
    public String sayHello(String hello) {
        return hello + "=== two";
    }
}

自定义注解

java 复制代码
package com.zsp.sheji.JavaSPI;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Pay {
    String type();
}

上下文

java 复制代码
package com.zsp.sheji.JavaSPI;

import org.springframework.stereotype.Component;

@Component
public class PayContext {

    private HelloService helloService;

    public void setHelloService(HelloService helloService){
        this.helloService = helloService;
    }

    public PayContext(){}

    public String sayHello(String hello){
        // 上下文进行数据承接
        return this.helloService.sayHello(hello);
    }
}

策略工厂

java 复制代码
package com.zsp.sheji.JavaSPI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;

public class PayFactory {
    private static Map<String,HelloService> helloMap = new HashMap<>();

    static {
        ServiceLoader<HelloService> load = ServiceLoader.load(HelloService.class);
        Iterator<HelloService> iterator = load.iterator();
        while (iterator.hasNext()) {
            HelloService next = iterator.next();
            Class<? extends HelloService> aClass = next.getClass();
            if (!aClass.isAnnotationPresent(com.zsp.sheji.JavaSPI.Pay.class)) {
                // 不存在添加进去
                throw new IllegalStateException("class: " + aClass + " expect @com.zsp.sheji.策略模式高级注解方式.PayType, but not found!");
            }
            helloMap.put(aClass.getAnnotation(Pay.class).type(), next);
        }
    }

    public static HelloService makeHello(String type){
        return helloMap.get(type);
    }
}

Java SPI配置

文件名:com.zsp.sheji.JavaSPI.HelloService 对应接口的全限定类名

java 复制代码
com.zsp.sheji.JavaSPI.HelloOneServiceImpl
com.zsp.sheji.JavaSPI.HelloTwoServiceImpl

项目结构

验证

相关推荐
意法半导体STM324 天前
【官方原创】如何为STM32CubeMX2配置Visual Studio Code配置方案
vscode·stm32·单片机·嵌入式硬件·策略模式·stm32cubemx·嵌入式开发
山东点狮信息科技有限公司5 天前
企业级 MES 制造执行系统架构设计与实践
spring cloud·性能优化·系统架构·策略模式·点狮
zzqssliu5 天前
基于策略模式与责任链的代购商品多源采集架构实战
架构·策略模式
mxpan6 天前
macOS 13+ 上使用 macFUSE + NTFS-3G 读写 NTFS 移动硬盘技术说明
macos·策略模式
折哥的程序人生 · 物流技术专研6 天前
Java 23 种设计模式:从踩坑到精通 | 番外:编排器+策略模式在多平台电子面单中的实战(含性能压测)
设计模式·策略模式·代码重构·java设计模式·编排器·电子面单·从踩坑到精通
忧云7 天前
2026年最新 Cursor 国内使用 DeepSeek API等各模型使用完整教程
ai编程·策略模式·cursor·byok·cursor使用国内大模型
AIex-YH7 天前
三域贯通11/12:生物制造的“死亡之谷“,CDMO 是桥还是船?
运维·制造·策略模式
回忆2012初秋8 天前
【Nginx】原理、配置与运维实战(2)
运维·nginx·策略模式
怎么没有名字注册了啊8 天前
macOS 基于 CSDN GitCode + Homebrew Tap 发布 Qt .app 二进制程序通用教程(homebrew 安装自己的软件)
策略模式·homebrew·formula·ruhy
坏小虎9 天前
macOS 安装 Ghostty 终端完整教程:环境、依赖与美化配置
macos·策略模式