当前位置: 首页 > news >正文

策略模式实战:Spring中动态选择商品处理策略的实现

概念

可以在运行时期动态的选择需要的具体策略类,处理具体的问题

组成元素

策略接口

public interface GoodsStrategy {void handleGoods();
}

具体策略类

@Service(Constants.BEAN_GOODS)
public class BeanGoodsStrategy implements GoodsStrategy {@Overridepublic void handleGoods() {System.out.println("处理金豆啦~~~~~");}
}
@Service(Constants.MEMBER_GOODS)
public class MemberGoodsStrategy implements GoodsStrategy {@Overridepublic void handleGoods() {System.out.println("会员商品");}
}
@Service(Constants.MEMBER_PLUS_GOODS)
public class MemberPlusGoodsStrategy implements GoodsStrategy {@Overridepublic void handleGoods() {System.out.println("会员积分商品");}
}

 上下文工厂类

@Service
public class GoodsStrategyFactory {@Autowiredprivate Map<String, GoodsStrategy> goodsStrategyMap;public GoodsStrategy getGoodsStrategy(String goodsType) {return goodsStrategyMap.get(goodsType);}
}

解释

在Spring框架中,通过 @Autowired 注入的 Map<String, GoodsStrategy> 会自动将 GoodsStrategy 接口的所有实现类注入到Map中,其中:

  • Key:Bean的名称(默认是类名首字母小写,或通过 @Component("自定义名称") 指定)。
  • Value:GoodsStrategy 接口的具体实现类的实例。

获取策略类处理业务

	@Testvoid test() {GoodsStrategy goodsStrategy = goodsStrategyFactory.getGoodsStrategy(Constants.MEMBER_GOODS);if (goodsStrategy != null){goodsStrategy.handleGoods();}}

 

http://www.xdnf.cn/news/925381.html

相关文章:

  • 软件测试—学习Day10
  • 开疆智能Ethernet/IP转Modbus网关连接MAG8000电池流量计配置案例
  • python版若依框架开发:集成Dash应⽤
  • 将 Elastic 的数据摄取转向 OpenTelemetry
  • SWE-Dev:开启自主特征驱动软件开发新纪元,重新定义大模型编码能力边界
  • 理解 RAG_HYBRID_BM25_WEIGHT:打造更智能的混合检索增强生成系统
  • 【Go核心编程】第十三章:接口与多态——灵活性的艺术
  • FUSSNet复现
  • vue注册自定义指令
  • 黄柏基因组-小檗碱生物合成的趋同进化-文献精读142
  • h5 安卓手机去掉滚动条问题
  • compose 组件 ---无ui组件
  • 基于TarNet、CFRNet与DragonNet的深度因果推断模型全解析
  • Python基于Django的文件销毁系统【附源码、文档说明】
  • Qwen 大模型-对话模板中system与user的区别解析
  • 并发编程实战(生产者消费者模型)
  • conda环境配置(二) —— 报错
  • QuickJS 如何发送一封邮件 ?
  • 区块链技术概述
  • Global Security Market知识点总结:主经纪商业务
  • 提高Python编程效率的工具推荐
  • Windows 系统安装 Redis 详细教程
  • 启程:为何选择PHP?
  • STM32学习笔记:定时器(TIM)原理与应用(详解篇)
  • Python入门手册:异常处理
  • 华为OD机试_2025 B卷_人民币转换(Python,100分)(附详细解题思路)
  • 生物发酵展同期举办2025中国合成生物学与生物制造创新发展论坛
  • 36、stringstream
  • AI编程提示词
  • 数据结构测试模拟题(4)