Spring Boot 整合工厂模式和策略模式完成服务调用的一种实现
工厂模式是一种创建型设计模式,其主要目的是提供一个创建对象的接口,但将具体类的实例化延迟到子类中。这样,客户端代码就不需要知道要实例化的具体类,只需要知道使用的工厂接口。
以前我们写代码的时候会经常用到if esle if,比如要判断十多种类型,每个类型都要使用if else if来判断,判断里面又有写大量的逻辑,代码耦合性太高,不利于后期拓展。策略模式就是解决这个问题的,讲每个判断逻辑单独抽取出来,通过类型直接去执行这个逻辑的代码块。
下面用工厂模式和策略模式解决上面的问题
项目结构如下
代码实例如下
所有水果都要实现这个接口
public interface AllFruits {
void eatFruits();
}
实现类如下
public class AppleFruit implements AllFruits {
@Override
public void eatFruits() {
System.out.println("吃苹果");
}
}
@Service
public class BananaFruit implements AllFruits {
@Override
public void eatFruits() {
System.out.println("吃香蕉");
}
}
@Service
public class OrangeFruit implements AllFruits {
@Override
public void eatFruits() {
System.out.println("吃橙子");
}
}
@Service
public class WatermelonFruit implements AllFruits {
@Override
public void eatFruits() {
System.out.println("吃西瓜");
}
}
然后将实现类存储到一个map中保存以备使用,key记录水果的类型,value为实现类
public class FruitsConfig {
protected static Map<Integer, AllFruits> fruitsMap = new ConcurrentHashMap<>();
@Autowired
private AppleFruit appleFruit;
@Autowired
private BananaFruit bananaFruit;
@Autowired
private OrangeFruit orangeFruit;
@Autowired
private WatermelonFruit watermelonFruit;
@PostConstruct
public void init() {
fruitsMap.put(1, appleFruit);
fruitsMap.put(2, bananaFruit);
fruitsMap.put(3, orangeFruit);
fruitsMap.put(4, watermelonFruit);
}
}
下面是工厂类
@Service
public class FruitsFactory extends FruitsConfig{
public AllFruits getFruit(Integer fruitType){
return fruitsMap.get(fruitType);
}
}
测试类完成测试,传入一个类型标识即可调用到对应的类
@SpringBootTest
class DemoApplicationTests {
@Autowired
private FruitsFactory fruitsFactory;
@Test
void testFruits() {
AllFruits fruit = fruitsFactory.getFruit(1);
fruit.eatFruits();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix