注解实现策略模式

注解实现策略模式

        • [1. 使用idea创建sprignboot项目](#1. 使用idea创建sprignboot项目)
        • [2. 创建策略接口](#2. 创建策略接口)
        • [3. 创建策略类型注解](#3. 创建策略类型注解)
        • [4. 创建两个具体策略类](#4. 创建两个具体策略类)
        • [5. 策略工厂类](#5. 策略工厂类)
        • [6. 使用](#6. 使用)
1. 使用idea创建sprignboot项目
2. 创建策略接口
java 复制代码
public interface Handler {

    Double callPrice(Double price);

}
3. 创建策略类型注解
java 复制代码
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface HandlerType {

    String type();
}
4. 创建两个具体策略类
java 复制代码
@HandlerType(type = "vip")
@Service
public class VipHandler implements Handler{
    @Override
    public Double callPrice(Double price) {
        return price*0.8;
    }
}
java 复制代码
@HandlerType(type="member")
@Service
public class MemberHandler implements Handler{
    @Override
    public Double callPrice(Double price) {
        return price;
    }
}
5. 策略工厂类
java 复制代码
@Component
public class HandlerFactory implements BeanFactoryPostProcessor {

    private static Map<String,Handler> handlerMap = new ConcurrentHashMap<>();
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        Map<String, Object> handlerBeans = beanFactory.getBeansWithAnnotation(HandlerType.class);
        Optional.ofNullable(handlerBeans).orElse(Collections.emptyMap())
                .forEach((name,bean) -> {
                    Class<?> clazz = bean.getClass();
                    HandlerType handlerType = clazz.getAnnotation(HandlerType.class);
                    handlerMap.put(handlerType.type(), (Handler) bean);
                });

    }

    public static Handler getHandler(String type){
        Handler handler = handlerMap.get(type);
        if (handler == null) {
            throw new RuntimeException("can not find handler");
        }
        return handler;
    }
}
6. 使用
java 复制代码
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        Handler vip = HandlerFactory.getHandler("vip");
        System.out.println(vip.callPrice(1000.0));
    }

}
相关推荐
开心香辣派小星16 小时前
23种设计模式-19策略模式(Strategy Pattern)
java·设计模式·策略模式
weixin_462446235 天前
【原创实践】python版playwright截取多个图
开发语言·python·策略模式
MC丶科6 天前
Java设计模式漫画英雄宇宙之策略模式:从支付系统重构到软考高频考点(附完整代码 + 面试高频问法)
java·设计模式·重构·策略模式
benxin12346 天前
macOS 上使用 Homebrew 安装和配置 PostgreSQL 的详细步骤
macos·postgresql·策略模式
佛祖让我来巡山8 天前
设计模式深度解析:策略模式、责任链模式与模板模式
设计模式·责任链模式·策略模式·模版模式
王柏龙10 天前
Win11 无法找到本地组策略编辑器的解决方法
windows·策略模式
hai-chu11 天前
将 Neo4j 安装为 macOS 服务
macos·策略模式·neo4j
6***x54514 天前
Java设计模式之策略模式
java·设计模式·策略模式
miss_you121314 天前
策略模式 + 模板方法 + 注册式工厂 统一设计方案(营销优惠场景示例)
设计模式·工厂方法模式·策略模式·模板方法模式
章鱼哥73014 天前
Java 策略模式 + 聚合对象:实现多模块的统计与聚合,快速扩展的实战
java·开发语言·策略模式