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!"
    }
相关推荐
Moe4881 分钟前
Redis 缓存三大经典问题:穿透、击穿与雪崩
java·后端·面试
我爱娃哈哈4 分钟前
SpringBoot + JSON 字段 + MySQL 8.0 函数索引:灵活存储半结构化数据,查询不慢
后端
赫瑞19 分钟前
Java中的最长公共子序列——LCS
java·开发语言
于先生吖22 分钟前
零基础开发国际版同城出行平台 JAVA 顺风车预约系统实战教学
java·开发语言
代码雕刻家22 分钟前
2.22.StringBuffer类的常见用法、
java·开发语言
yhole23 分钟前
Java进阶(ElasticSearch的安装与使用)
java·elasticsearch·jenkins
明月(Alioo)38 分钟前
Python 并发编程详解 - Java 开发者视角
java·开发语言·python
0xDevNull1 小时前
基于Java的小程序地理围栏实现原理
java·小程序
arvin_xiaoting1 小时前
OpenClaw学习总结_II_频道系统_5:Signal集成详解
java·前端·学习·signal·ai agent·openclaw·signal-cli
凌波粒1 小时前
LeetCode--19.删除链表的倒数第 N 个结点(链表)
java·算法·leetcode·链表