SpringBoot工厂模式

前言

下面的示例展示了 SpringBoot 中如何使用工厂模式,该示例通过 ApplicationContext 直接获取 Spring 容器中所有 Animal 的 Bean,然后将它们存储在 animalMap 中,使用时直接从 Map 中获取实例。

另一种工厂模式可参考我另一篇文章 :SpringBoot 工厂模式自动注入到Map

一、建立父类

java 复制代码
public abstract class Animal {
    public abstract void makeSound();
    public abstract String getType();
}

二、两个子类

java 复制代码
@Component
public class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Miao!");
    }

    @Override
    public String getType() {
        return "cat";
    }
}
java 复制代码
@Component
public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Wang!");
    }

    @Override
    public String getType() {
        return "dog";
    }
}

三、工厂类注入到 map 里

java 复制代码
@Component
public class AnimalFactory implements ApplicationContextAware, InitializingBean {
    private final Map<String, Animal> animalMap = new ConcurrentHashMap<>();

    private ApplicationContext appContext;

    public Animal getAnimal(String animalType) {
        Animal animal = this.animalMap.get(animalType);
        if (animal == null) {
            throw new IllegalArgumentException("Unsupported animal type: " + animalType);
        }
        return animal;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, Animal> beansOfType = this.appContext.getBeansOfType(Animal.class);
        beansOfType.values().forEach(animal -> animalMap.put(animal.getType(), animal));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.appContext = applicationContext;
    }
}

四、测试

java 复制代码
	@Autowired
    private AnimalFactory animalFactory;
	
	
    public void printSound() throws Exception {
        Animal animal_1 = animalFactory.getAnimal("dog");
        animal_1.makeSound(); // 输出 "Wang!"

        Animal animal_2 = animalFactory.getAnimal("cat");
        animal_2.makeSound(); // 输出 "Miao!"
    }
相关推荐
何以解忧,唯有..4 分钟前
高并发下超卖问题解决方案:从数据库到分布式锁的完整实践
java
ServBay16 分钟前
ServBay 1.33.0 来了:AI Gateway 一键接管主流 AI CLI 与多模型
后端·aigc·ai编程
行者全栈架构师17 分钟前
Spring Boot 接入 MaxKey 单点登录:6 个内部系统,一次登录全通行
java·vue.js·后端
JuiceFS20 分钟前
卓驭:百 PB 级智驾数据存储架构演进
后端·自动驾驶
鱼弦22 分钟前
跨模态迁移的极限:语言模型的逻辑能力能否完全迁移到视觉?
后端
ModStart25 分钟前
写歌、翻唱、可编辑乐谱,YuE2-3B 在 AIGCPanel 一键跑通
后端
故作春风27 分钟前
elpis-core 核心从入门到理解
后端·架构·node.js
木白CPP34 分钟前
Linux DMA驱动详解(二)-----DMA的使用者
java·linux·运维
caoerzhong38 分钟前
JeeWMS 开源仓库管理系统 GPL-3.0 合规指南:Java WMS 二次开发前必须弄清的授权边界
java·开发语言·开源·vue
LEE40 分钟前
前端转型全栈 01:数据建模,前端最大的盲区
前端·javascript·后端