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

概念

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

组成元素

策略接口

java 复制代码
public interface GoodsStrategy {
	void handleGoods();
}

具体策略类

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

上下文工厂类

java 复制代码
@Service
public class GoodsStrategyFactory {

    @Autowired
    private 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 接口的具体实现类的实例。

获取策略类处理业务

java 复制代码
	@Test
	void test() {
		GoodsStrategy goodsStrategy = goodsStrategyFactory.getGoodsStrategy(Constants.MEMBER_GOODS);
		if (goodsStrategy != null){
			goodsStrategy.handleGoods();
		}
	}
相关推荐
七月丶3 小时前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞3 小时前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼3 小时前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
SimonKing4 小时前
OpenCode AI辅助编程,不一样的编程思路,不写一行代码
java·后端·程序员
FastBean4 小时前
Jackson View Extension Spring Boot Starter
java·后端
Seven975 小时前
剑指offer-79、最⻓不含重复字符的⼦字符串
java
皮皮林55114 小时前
Java性能调优黑科技!1行代码实现毫秒级耗时追踪,效率飙升300%!
java
冰_河15 小时前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化
桦说编程18 小时前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读